问:
How to check for successful response from API in rails by just using status code?
I am consuming an API using a gem in Ruby on Rails. The gem makes the API call for me and returns the status code as an integer (for example 200, 201 e.t.c.) and the data response from the API.

```<code>def get_cars
  status_code, data = MyGem::Cars.get_cars
  if status_code in SUCCESSFUL_RESPONSE_CODES
    # Perform data manipulation
  else
    raise "There was an error processing the request. Status code #{status_code}"
  end
end
</code>```

Now I have manually initialised SUCCESSFUL_RESPONSE_CODES as a list containing integers of successful codes I found here.

Is this list defined somewhere in Ruby/RoR to avoid manually defining it?

答:
I would expect any widely supported gem to use standard HTTP response codes to determine if the HTTP response was a success.  For example:

```<code>require 'open-uri' # Rails loads this by default.
res = open('http://example.com')
res.status
=> ["200","OK"]
status.include?'OK'
=>true
status.include?'200'
=> true
</code>```

So long as you trust the gem code making your request to handle standard HTTP response codes, you should be ok.  Here's another example using HTTParty gem

```<code>require 'HTTParty'
res = HTTParty.get('https://example.com')
res.success?
=> true
</code>```

Body:
I am consuming an API using a gem in Ruby on Rails. The gem makes the API call for me and returns the status code as an integer (for example 200, 201 e.t.c.) and the data response from the API.

def get_cars
  status_code, data = MyGem::Cars.get_cars
  if status_code in SUCCESSFUL_RESPONSE_CODES
    # Perform data manipulation
  else
    raise "There was an error processing the request. Status code #{status_code}"
  end
end

Now I have manually initialised SUCCESSFUL_RESPONSE_CODES as a list containing integers of successful codes I found here.

Is this list defined somewhere in Ruby/RoR to avoid manually defining it?

Body:
I would expect any widely supported gem to use standard HTTP response codes to determine if the HTTP response was a success.  For example:

require 'open-uri' # Rails loads this by default.
res = open('http://example.com')
res.status
=> ["200","OK"]
status.include?'OK'
=>true
status.include?'200'
=> true

So long as you trust the gem code making your request to handle standard HTTP response codes, you should be ok.  Here's another example using HTTParty gem

require 'HTTParty'
res = HTTParty.get('https://example.com')
res.success?
=> true


来源: stackexchange

问:
Jquery hide and show in one line
I need to build function that show or hide element following a boolean flag.
flag==false: hide
flag==true: show
the function should contain only single line that will starts with: $element.

I need to complete:

```<code>function willItShow($element, flag){
    $element
}
</code>```

please help me with it.
thank you all!!

答:
Hey if it needs to be a one liner you can use an inline if like so

CODE:

```<code>function willItShow($element, flag){
  $element && flag === false ? $element.hide() : $element.show() ;
}
</code>```

Explanation:

$element && flag === false means that if $element is defined and the flag === false it will hide the element, otherwise if flag is true or element is not defined it will try to show, there is nothing there so it will show nothing

Happy hacking :)

ContentLicense: CC BY-SA 4.0

Title: Jquery hide and show in one line

Body:
I need to build function that show or hide element following a boolean flag.
flag==false: hide
flag==true: show
the function should contain only single line that will starts with: $element.

I need to complete:

function willItShow($element, flag){
    $element
}

please help me with it.
thank you all!!

Body:
Hey if it needs to be a one liner you can use an inline if like so

CODE:

function willItShow($element, flag){
  $element && flag === false ? $element.hide() : $element.show() ;
}

Explanation:

$element && flag === false means that if $element is defined and the flag === false it will hide the element, otherwise if flag is true or element is not defined it will try to show, there is nothing there so it will show nothing

Happy hacking :)


问:
How to make a webpage unresponsive?
I'm looking to make my webpage unresponsive in the sense to where upon a window resize, rather than elements changing properties & using media queries, I want the entire page to just scale down proportionally and all elements keep their ratio. How is this done? with pure css or with the aid of JS?</p>

答: I'm no master at HTML, but maybe you could try percentages? as your values for your width,height,etc. </p>

Title: How to make a webpage unresponsive?


问:
default access modifier for interface member
I'm new to C#, just a question on default access modifier for interface member.
We know that the default access modifier for interface is "internal", but why the default access modifier for interface member is "public"? shouldn't it be "internal" so it can be consistent?</p>

答:
Interfaces declared directly within a namespace can be declared as
  public or internal and, just like classes and structs,
  interfaces default to internal access. Interface members are always
  public because the purpose of an interface is to enable other
  types to access a class or struct. No access modifiers can be
  applied to interface members.

For more information about Access Modifiers (C# Programming Guide) check the following link


问:
Can i wirte follow/unfollow bot with Instagram?
I want to Write Bot for Follow/Unfollow user in instagram , but instagram Api deprecated Follow and Relationships ...

can i use instagram Api for this goal or must be use selenium automation ?!

答:
As per this article the Instagram API no longer provides functionality to follow or unfollow users. Looking at the current endpoints provided by the Instagram API the set of operations looks very limited - fetch a user, or a user's latest media, and get a list of comments on your media. You can view the changelog for the Instagram API here.

So to answer your question, no you can no longer use a bot to follow or unfollow a user via the Instagram API. Yes you will be able to write a Selenium script that will do this.


问:
Should I call the database connection setup in each method or just once in constructor
I'm working on a small project in Java and I have got DatabaseController class which contains many methods to insert/select/delete from my database.

my question is, related to setting up the connection in regards to best software engineering practices.

Should I establish the database connection in DatabaseController constructor so it's opened once and left open Or..

Should I place a method to connect to the database before my insert/delete/select methods?

I understand that both might have cons and pros .. but I'd like to know what's best for small and large scale projects?

答:
DataSource

Firstly, it is best to put access to your database behind a DataSource interface. This gives you the power to change your strategy for getting a database connection without changing all the many places in your code where you use those database connections. See Oracle Tutorial.

Your JDBC driver should provide an implementation of DataSource. For example, consider the Postgres JDBC driver from https://jdbc.postgresql.org. That driver supplies two implementations: One for direct connections to the database, and the other for pooling connections. By using the DataSource as a façade, you could switch between either of these, or even use a 3rd party connection pooling solution, in one place in your code, without changing the many places you call DataSource::getConnection().

A third kind of implementation you might want to substitute in would be for distributed transactions.

Another example of swapping the concrete class behind the interface: Perhaps you decide to switch JDBC drivers. Perhaps for your Postgres database, you decide to switch from the jdbc.postgresql.org driver to the pgjdbc-ng driver. You want to be able to make this configuration change in one place, without breaking all your existing app code.

Here is an example of using a concrete implementation behind the DataSource interface.

```<code>public javax.sql.DataSource obtainDataSource() {
    org.postgresql.ds.PGSimpleDataSource dataSource = new PGSimpleDataSource() ;
    dataSource("AcmeInvoices database data source") ;
    source.setServerName( "localhost" ) ;
    source.setDatabaseName( "invoicing" ) ;
    source.setUser( "Scott" ) ;
    source.setPassword( "tiger" ) ;
    return dataSource ;  // Returning a reference to the object of this concrete class `PGSimpleDataSource` as an object of the interface `DataSource`.
}
</code>```

The methods you see being called in that code snippet above will vary dramatically by the capabilities of your database and of your JDBC driver. For example, if you are using encrypted connections to the database, you will have additional methods to call for configuring the encryption keys.

You set up this DataSource object early on, likely as part of your app launch. Keep a reference someplace. Or keep several: you may have different connection types (different user name & passwords) for different parts of your app where different security or different user roles are necessary.

Pass the DataSource object around your codebase to the many methods that insert/select/delete with your database. In each method, they call myDataSource.getConnection(), then go on to execute their SQL. When that method finishes its work, it should close the connection by calling Connection::close. Even better, use try-with-resources to automatically close the connection.

If the connection came from a connection pool, the connection is not really closed. Rather, the connection is returned to the pool. This is another example of the power of using an interface, here Connection. The concrete class behind the interface can choose how to respond to invoking the close method — and that concrete class can be swapped out later without breaking the calling code.

Open connections

Should I establish the database connection in DatabaseController constructor so it's opened once and left open

No, it is not generally a good idea to keep a connection open with no further work to be done.

Basically you would be creating your own connection pool. And connection pooling is not a simple matter. There are various issues to consider in pooling, and you are unlikely to think of them much less be competent to solving them. All the connection pooling tools I have seen have each had their share of bugs, issues, and limitations. So do not take on this task yourself. If you do choose to go with pooling, find a robust well-worn existing implementation. And study its documentation thoroughly to be sure you understand how to configure and use the pool properly.

Frankly, I stopped using connection pooling myself. The various risks and complications are not worth it in my opinion for systems with a lower number of less frequent number of users/connections. For example, look at the default time-out set in the various pooling solutions where the pooled connections are closed after some period of no use. If your activity in the pool is mostly lower than that time-out, then you effectively won't be benefiting from the pool. Also, I have found that most of the claims about opening a connection to the database as expensive are exaggerated, especially for a local database on the same machine.

Examples

Should I place a method to connect to the database before my insert/delete/select methods

Here are some example scenarios showing how you should get-and-close the database connection close to where you use the connection for some specific database task.

In your login screen where you authenticate the user by looking up users and groups stored in your database, when the user clicks the Login button, your code should retrieve a reference to the DataSource object, call getConnection, do the user-and-groups lookups, then immediately close the connection.

When the user goes on to lookup overdue invoices, do the same. Retrieve the DataSource, call getConnection, run your SQL to find any overdue invoices, load that invoice data into memory as a cache, call Connection::close to close the connection to the database, and proceed to build your GUI to display the cached invoice data.

When the user clicks a button to take some action on one of those invoices, do the same process. Retrieve the DataSource, call getConnection, run your SQL to fetch the particular invoice row for the desired primary key value, retrieve additional invoice fields and related rows such as invoice-items, call Connection::close to close the connection to the database, and proceed with your action such as generating an email containing the cached invoice details and its invoice-item rows. Notice how you might use the connection multiple times within this action method, first to hit the invoice table, then again to hit the invoice-item table. When finally all the immediate work at hand is complete, close the connection.

Remember, in each of these several times where you got a connection and closed a connection, if pooled:

You are getting a connection that may or may not be new.

“Closing” returns the connection to the pool rather than actually closing it.

The pool may close the connection at some point, and at some point perhaps replace it with a fresh connection. But that is transparent to all your user-authentication code and invoice lookup code.

Body:
DataSource

Firstly, it is best to put access to your database behind a DataSource interface. This gives you the power to change your strategy for getting a database connection without changing all the many places in your code where you use those database connections. See Oracle Tutorial.

Your JDBC driver should provide an implementation of DataSource. For example, consider the Postgres JDBC driver from https://jdbc.postgresql.org. That driver supplies two implementations: One for direct connections to the database, and the other for pooling connections. By using the DataSource as a façade, you could switch between either of these, or even use a 3rd party connection pooling solution, in one place in your code, without changing the many places you call DataSource::getConnection().

A third kind of implementation you might want to substitute in would be for distributed transactions.

Another example of swapping the concrete class behind the interface: Perhaps you decide to switch JDBC drivers. Perhaps for your Postgres database, you decide to switch from the jdbc.postgresql.org driver to the pgjdbc-ng driver. You want to be able to make this configuration change in one place, without breaking all your existing app code.

Here is an example of using a concrete implementation behind the DataSource interface.

public javax.sql.DataSource obtainDataSource() {
    org.postgresql.ds.PGSimpleDataSource dataSource = new PGSimpleDataSource() ;
    dataSource("AcmeInvoices database data source") ;
    source.setServerName( "localhost" ) ;
    source.setDatabaseName( "invoicing" ) ;
    source.setUser( "Scott" ) ;
    source.setPassword( "tiger" ) ;
    return dataSource ;  // Returning a reference to the object of this concrete class `PGSimpleDataSource` as an object of the interface `DataSource`.
}

The methods you see being called in that code snippet above will vary dramatically by the capabilities of your database and of your JDBC driver. For example, if you are using encrypted connections to the database, you will have additional methods to call for configuring the encryption keys.

You set up this DataSource object early on, likely as part of your app launch. Keep a reference someplace. Or keep several: you may have different connection types (different user name & passwords) for different parts of your app where different security or different user roles are necessary.

Pass the DataSource object around your codebase to the many methods that insert/select/delete with your database. In each method, they call myDataSource.getConnection(), then go on to execute their SQL. When that method finishes its work, it should close the connection by calling Connection::close. Even better, use try-with-resources to automatically close the connection.

If the connection came from a connection pool, the connection is not really closed. Rather, the connection is returned to the pool. This is another example of the power of using an interface, here Connection. The concrete class behind the interface can choose how to respond to invoking the close method — and that concrete class can be swapped out later without breaking the calling code.

Open connections

Should I establish the database connection in DatabaseController constructor so it's opened once and left open

No, it is not generally a good idea to keep a connection open with no further work to be done.

Basically you would be creating your own connection pool. And connection pooling is not a simple matter. There are various issues to consider in pooling, and you are unlikely to think of them much less be competent to solving them. All the connection pooling tools I have seen have each had their share of bugs, issues, and limitations. So do not take on this task yourself. If you do choose to go with pooling, find a robust well-worn existing implementation. And study its documentation thoroughly to be sure you understand how to configure and use the pool properly.

Frankly, I stopped using connection pooling myself. The various risks and complications are not worth it in my opinion for systems with a lower number of less frequent number of users/connections. For example, look at the default time-out set in the various pooling solutions where the pooled connections are closed after some period of no use. If your activity in the pool is mostly lower than that time-out, then you effectively won't be benefiting from the pool. Also, I have found that most of the claims about opening a connection to the database as expensive are exaggerated, especially for a local database on the same machine.

Examples

Should I place a method to connect to the database before my insert/delete/select methods

Here are some example scenarios showing how you should get-and-close the database connection close to where you use the connection for some specific database task.

In your login screen where you authenticate the user by looking up users and groups stored in your database, when the user clicks the Login button, your code should retrieve a reference to the DataSource object, call getConnection, do the user-and-groups lookups, then immediately close the connection.

When the user goes on to lookup overdue invoices, do the same. Retrieve the DataSource, call getConnection, run your SQL to find any overdue invoices, load that invoice data into memory as a cache, call Connection::close to close the connection to the database, and proceed to build your GUI to display the cached invoice data.

When the user clicks a button to take some action on one of those invoices, do the same process. Retrieve the DataSource, call getConnection, run your SQL to fetch the particular invoice row for the desired primary key value, retrieve additional invoice fields and related rows such as invoice-items, call Connection::close to close the connection to the database, and proceed with your action such as generating an email containing the cached invoice details and its invoice-item rows. Notice how you might use the connection multiple times within this action method, first to hit the invoice table, then again to hit the invoice-item table. When finally all the immediate work at hand is complete, close the connection.

Remember, in each of these several times where you got a connection and closed a connection, if pooled:

You are getting a connection that may or may not be new.

“Closing” returns the connection to the pool rather than actually closing it.

The pool may close the connection at some point, and at some point perhaps replace it with a fresh connection. But that is transparent to all your user-authentication code and invoice lookup code.


问:
How to ignore storybook addon error in typescript?
I am using storybook in a typescript react project and I am facing some compiling error like

Could not find a declaration file for module '@storybook/addon-actions'. '/material-ui-es/node_modules/@storybook/addon-actions/dist/index.js' implicitly has an 'any' type.

They are from storybook addons. How can I fix the error if the addons doesn't support type. Or I'd like to ignore them since they are not part of production.

答:
I'm also using Storybook in my projects and to fix this problem I add types

```<code>"devDependencies": {
    ...
    "@types/storybook__addon-actions": "^3.4.2",
    "@types/storybook__react": "^4.0.1",
    "apollo-storybook-react": "^0.2.1",
    ...
},
</code>```

and if there are no types, I declare the module on typings.d.ts

```<code>declare module 'apollo-storybook-react';
declare module '@storybook/addon-console';
</code>```

Body:
I'm also using Storybook in my projects and to fix this problem I add types

"devDependencies": {
    ...
    "@types/storybook__addon-actions": "^3.4.2",
    "@types/storybook__react": "^4.0.1",
    "apollo-storybook-react": "^0.2.1",
    ...
},

and if there are no types, I declare the module on typings.d.ts

declare module 'apollo-storybook-react';
declare module '@storybook/addon-console';


问:
Calculate sentence from row to row in .txt file using vs code
I am doing the sentiment analysis. The initial code is just for a string. However, I want to make the program run and process the sentiment analysis for each sentence in a .csv file. The program is run using vs code.

Here is how I modified my code:

fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
    lines = fp.read().split("\n") # Create a list containing all lines
    fp.close() # Close file
    print(lines)
    print("----------------------------------------------------\n")

    # simple example to tokenize paragraph into sentences for VADER
    from nltk import tokenize

    sentence_list = tokenize.sent_tokenize(lines)
    paragraphSentiments = 0.0
    for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)

        print("{:-<69} {}".format(sentence, str(vs["compound"])))
        paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))
    print("----------------------------------------------------")
```

<p>I expect the output is sentiment analysis for each sentence in the .csv file. The errors I got are :</p>

``` File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 95, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 312, in _pair_iter
    prev = next(it)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object
```

答:
In your code lines is a list of strings, but sent_tokenize() is expecting a string.

You need something like:

```<code>for line in lines:
    sent_list = tokenize.sent_tokenize(line)
    for sent in sent_list:
        # do your stuff
</code>```

Hope this helps.

Body:
I am doing the sentiment analysis. The initial code is just for a string. However, I want to make the program run and process the sentiment analysis for each sentence in a .csv file. The program is run using vs code.

Here is how I modified my code:

fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
    lines = fp.read().split("\n") # Create a list containing all lines
    fp.close() # Close file
    print(lines)
    print("----------------------------------------------------\n")

    # simple example to tokenize paragraph into sentences for VADER
    from nltk import tokenize

    sentence_list = tokenize.sent_tokenize(lines)
    paragraphSentiments = 0.0
    for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)

        print("{:-<69} {}".format(sentence, str(vs["compound"])))
        paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))
    print("----------------------------------------------------")

I expect the output is sentiment analysis for each sentence in the .csv file. The errors I got are :

 File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 95, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 312, in _pair_iter
    prev = next(it)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object

Body:
In your code lines is a list of strings, but sent_tokenize() is expecting a string.

You need something like:

for line in lines:
    sent_list = tokenize.sent_tokenize(line)
    for sent in sent_list:
        # do your stuff

Hope this helps.


问:
Manipulate / set style shadowRoot using Puppeteer
I try to take Screenshots of AMP Stories, without the sound and share buttons.

After I found out that there is something called shadow DOM I wonder how to set display : none there:

```<code>addStyleTag({content: '.i-amphtml-story-system-layer-buttons { display : none!important }'})
</code>```

I think I made it to access the shadow DOM like this.

```<code>const shadowRootInnerHTML = await page.evaluate(() => {
    return document.querySelector("body > amp-story > div").shadowRoot.innerHTML
});
</code>```

This is what I'm using currently,

```<code>const browser = await puppeteer.launch({
  slowMo: 250,
  args: [
    '--disable-infobars',
  ]
});
const page = await browser.newPage()

await page.emulate({
  name: 'iPhone1080x1920',
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
  viewport: {
    width: 360,
    height: 640,
    deviceScaleFactor: 3,
    isLandscape: false
  }
});

await page.goto(urlToTest, {
  waitUntil: 'networkidle2',
  timeout: 0
});

const textContent = await page.evaluate(() => {
  return document.querySelector("body > amp-story > div").shadowRoot.innerHTML
});
</code>```

答:
Amp pages have multiple div elements inside amp-story.

We can execute this vanilla JavaScript which will hide away the top slide and share button on amp pages.

I have added two ways inside this code, you can apply either one.

```<code>// there are multiple div elements inside amp-story
const elements = [...document.querySelectorAll("body > amp-story > div")];

elements.map(rootElement => {
  // find the shadowRoot inside if it exists
  const shadowRoot = rootElement.shadowRoot;

  if (shadowRoot) {
    /**
     * WAY 1: Find the element and apply css to it directly
     */
    // this holds the top share button and pagination slides
    const element = shadowRoot.querySelector(
      ".i-amphtml-story-system-layer"
    );

    // forcefully hide the element
    if (element) element.style.setProperty("display", "none", "important");

    /**
     * WAY 2: Append your own style to the <style> tag inside the amp shadowRoot
     */
    shadowRoot.querySelector('style').innerHTML += `.i-amphtml-story-system-layer { display : none!important }`
  }
});
</code>```

Basically,

Find the div

Get the shadowRoot

Either find the element and apply directly, or add style to the  tag.

Result on a sample amp page:

Body:
I try to take Screenshots of AMP Stories, without the sound and share buttons.

After I found out that there is something called shadow DOM I wonder how to set display : none there:

addStyleTag({content: '.i-amphtml-story-system-layer-buttons { display : none!important }'})

I think I made it to access the shadow DOM like this.

const shadowRootInnerHTML = await page.evaluate(() => {
    return document.querySelector("body > amp-story > div").shadowRoot.innerHTML
});

This is what I'm using currently,

const browser = await puppeteer.launch({
  slowMo: 250,
  args: [
    '--disable-infobars',
  ]
});
const page = await browser.newPage()

await page.emulate({
  name: 'iPhone1080x1920',
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
  viewport: {
    width: 360,
    height: 640,
    deviceScaleFactor: 3,
    isLandscape: false
  }
});

await page.goto(urlToTest, {
  waitUntil: 'networkidle2',
  timeout: 0
});

const textContent = await page.evaluate(() => {
  return document.querySelector("body > amp-story > div").shadowRoot.innerHTML
});

Body:
Amp pages have multiple div elements inside amp-story.

We can execute this vanilla JavaScript which will hide away the top slide and share button on amp pages.

I have added two ways inside this code, you can apply either one.

// there are multiple div elements inside amp-story
const elements = [...document.querySelectorAll("body > amp-story > div")];

elements.map(rootElement => {
  // find the shadowRoot inside if it exists
  const shadowRoot = rootElement.shadowRoot;

  if (shadowRoot) {
    /**
     * WAY 1: Find the element and apply css to it directly
     */
    // this holds the top share button and pagination slides
    const element = shadowRoot.querySelector(
      ".i-amphtml-story-system-layer"
    );

    // forcefully hide the element
    if (element) element.style.setProperty("display", "none", "important");

    /**
     * WAY 2: Append your own style to the <style> tag inside the amp shadowRoot
     */
    shadowRoot.querySelector('style').innerHTML += `.i-amphtml-story-system-layer { display : none!important }`
  }
});

Basically,

Find the div

Get the shadowRoot

Either find the element and apply directly, or add style to the  tag.

Result on a sample amp page:


问:
How can I keep my iterable value in loop with React and Redux?
Everytime I click on the button the argument is always the last value of {i} (in this case is 0) and I need to have the ordinary value to pass to the Redux action.

When I print inside my DIV working.

```<code>class MYCLASS extends React.Component {
    constructor(props){
        super(props);
    }

    render() {
        var level = [];
        for (var i = 10; i > 0; i--) {
            level.push(
                <div>
                    <div>{i}</div>
                    <button className='up' onClick={()=>this.props.callUp({i})}>HEREEE!!</button>
                    <button className='down' onClick={()=>this.props.callDown({i})}>HEREEE!!</button>
                </div>
            );
        }
        return level
    }

}
const mapDispatchToProps = (dispatch) => ({
    callUp: (i) => dispatch(callUp(i)),
    callDown: (i) => dispatch(callDown(i)),
})
</code>```

答:
As you iterate through the loop you can store the value of i to a variable. Each time you iterate through the loop, you create a new instance of that variable. Then you can pass that variable into the onClick handler. Its current value will be used and stored in the memory of your array.

If you dont do this it will only use the final value of i

See codesandbox for reference: https://codesandbox.io/s/fancy-waterfall-kw0kb

```<code>import React from "react";

class Test extends React.Component {
  renderButtons = () => {
    var level = [];
    for (var i = 10; i > 0; i--) {
      const currentLevel = i;
      level.push(
        <div>
          <div>{currentLevel}</div>
          <button className="up" onClick={() => this.props.callUp(currentLevel) }>
            HEREEE!!
          </button>
          <button className="down" onClick={() => this.props.callDown(currentLevel) }>
            HEREEE!!
          </button>
        </div>
      );
    }
    return level;
  };

  render() {
    return <div>{this.renderButtons()}</div>;
  }
}

export default Test;

const mapDispatchToProps = (dispatch) => ({
  callUp: (i) => dispatch(callUp(i)),
  callDown: (i) => dispatch(callDown(i)),
})
</code>```

Body:
Everytime I click on the button the argument is always the last value of {i} (in this case is 0) and I need to have the ordinary value to pass to the Redux action.

When I print inside my DIV working.

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

    render() {
        var level = [];
        for (var i = 10; i > 0; i--) {
            level.push(

{i}

                    <button className='up' onClick={()=>this.props.callUp({i})}>HEREEE!!</button>
                    <button className='down' onClick={()=>this.props.callDown({i})}>HEREEE!!</button>

            );
        }
        return level
    }

}
const mapDispatchToProps = (dispatch) => ({
    callUp: (i) => dispatch(callUp(i)),
    callDown: (i) => dispatch(callDown(i)),
})

Body:
As you iterate through the loop you can store the value of i to a variable. Each time you iterate through the loop, you create a new instance of that variable. Then you can pass that variable into the onClick handler. Its current value will be used and stored in the memory of your array.

If you dont do this it will only use the final value of i

See codesandbox for reference: https://codesandbox.io/s/fancy-waterfall-kw0kb

import React from "react";

class Test extends React.Component {
  renderButtons = () => {
    var level = [];
    for (var i = 10; i > 0; i--) {
      const currentLevel = i;
      level.push(
        <div>
          <div>{currentLevel}</div>
          <button className="up" onClick={() => this.props.callUp(currentLevel) }>
            HEREEE!!
          </button>
          <button className="down" onClick={() => this.props.callDown(currentLevel) }>
            HEREEE!!
          </button>
        </div>
      );
    }
    return level;
  };

  render() {
    return <div>{this.renderButtons()}</div>;
  }
}

export default Test;

const mapDispatchToProps = (dispatch) => ({
  callUp: (i) => dispatch(callUp(i)),
  callDown: (i) => dispatch(callDown(i)),
})


问:
Mapping function to list/array in haskell?
I am trying to make Conway's Game of Life in Haskell. I am very new to Haskell and functional programming in general, and having trouble making an array in haskell to represent the game board.

I am trying to initiate a random array to begin the game. To do that I create a function randomBoard which returns '*' or ' ' to represent a space on the game board.

I want to be able to create the game board array with this function. I havent been able to succesfully instantiate an array yet. I am hoping there is a way i can declare an array of say size 100 and use my random function to set each element.

```<code>import System.Random
import Data.Array
import Data.List

randomBoard =
   do
   f1 <- randomIO :: IO Int
   if(f1 `mod` 2) == 0
     then return  '*'
     else return  ' '

boardArray :: Array Int Char
boardArray = listArray (0, 100) . map randomBoard $ 100 (0,100)
</code>```

This obviously doesnt work or even compile. I am sure there are a couple things wrong with it, as I am not sure really how to even work with IO in haskell and produce this outcome. Any guidance is much appreciated...

答:
This should work for you:

```<code>import Control.Monad
import System.Random
import Data.Array
import Data.List

randomBoard :: IO Char
randomBoard =
   do
   f1 <- randomIO :: IO Int
   if(f1 `mod` 2) == 0
     then return  '*'
     else return  ' '

boardArray :: IO (Array Int Char)
boardArray = listArray (0, 99) <$> replicateM 100 randomBoard
</code>```

Here's what I changed:

I added the type signature randomBoard :: IO Char for clarity. (The code would still work without it, as Haskell correctly infers this type if you don't supply it.)

I changed the type of boardArray to use IO. Anything that uses IO, no matter how indirectly, need to be in IO itself.

I changed listArray (0, 100) to listArray (0, 99), as the former would actually be 101 elements.

map randomBoard $ 100 (0,100) isn't right at all. To get a list of several of the same thing, you'd usually use replicate, but since the thing you care about here is in the IO monad, you use replicateM instead. replicateM 100 randomBoard gives an IO [Char] with 100 random elements of either '*' or ' '.

I added an import of Control.Monad, which is needed to use replicateM.

I use <$> in boardArray. Since you want to call listArray with a [Char] and get an Array Int Char, but replicateM 100 randomBoard is an IO [Char], you can't just apply the argument directly. Using <$> (which is also called fmap) applies it "inside" of IO, giving you back an IO (Array Int Char).

Body:
I am trying to make Conway's Game of Life in Haskell. I am very new to Haskell and functional programming in general, and having trouble making an array in haskell to represent the game board.

I am trying to initiate a random array to begin the game. To do that I create a function randomBoard which returns '*' or ' ' to represent a space on the game board.

I want to be able to create the game board array with this function. I havent been able to succesfully instantiate an array yet. I am hoping there is a way i can declare an array of say size 100 and use my random function to set each element.

import System.Random
import Data.Array
import Data.List

randomBoard =
   do
   f1 <- randomIO :: IO Int
   if(f1 `mod` 2) == 0
     then return  '*'
     else return  ' '

boardArray :: Array Int Char
boardArray = listArray (0, 100) . map randomBoard $ 100 (0,100)

This obviously doesnt work or even compile. I am sure there are a couple things wrong with it, as I am not sure really how to even work with IO in haskell and produce this outcome. Any guidance is much appreciated...

Body:
This should work for you:

import Control.Monad
import System.Random
import Data.Array
import Data.List

randomBoard :: IO Char
randomBoard =
   do
   f1 <- randomIO :: IO Int
   if(f1 `mod` 2) == 0
     then return  '*'
     else return  ' '

boardArray :: IO (Array Int Char)
boardArray = listArray (0, 99) <$> replicateM 100 randomBoard

Here's what I changed:

I added the type signature randomBoard :: IO Char for clarity. (The code would still work without it, as Haskell correctly infers this type if you don't supply it.)

I changed the type of boardArray to use IO. Anything that uses IO, no matter how indirectly, need to be in IO itself.

I changed listArray (0, 100) to listArray (0, 99), as the former would actually be 101 elements.

map randomBoard $ 100 (0,100) isn't right at all. To get a list of several of the same thing, you'd usually use replicate, but since the thing you care about here is in the IO monad, you use replicateM instead. replicateM 100 randomBoard gives an IO [Char] with 100 random elements of either '*' or ' '.

I added an import of Control.Monad, which is needed to use replicateM.

I use <$> in boardArray. Since you want to call listArray with a [Char] and get an Array Int Char, but replicateM 100 randomBoard is an IO [Char], you can't just apply the argument directly. Using <$> (which is also called fmap) applies it "inside" of IO, giving you back an IO (Array Int Char).


问:
Passport Google strategy - when does the passport.use callback run? The callbackURL?
I'm using Passport and working on the Google OAuth 2 strategy. I'm having trouble understanding the flow.

Here is the code in the official docs:

```<code>var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://www.example.com/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, done) {
       User.findOrCreate({ googleId: profile.id }, function (err, user) {
         return done(err, user);
       });
  }
));
</code>```

And then this for the routes:

```<code>// GET /auth/google
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Google authentication will involve
//   redirecting the user to google.com.  After authorization, Google
//   will redirect the user back to this application at /auth/google/callback
app.get('/auth/google',
  passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

// GET /auth/google/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });
</code>```

Here's my understanding of the flow. User clicks a button to log in with google on the browser. Request is sent to /auth/google. Which calls passport.authenticate. From there, Google handles some stuff and once the user gives us permission to access their Google account, well, that's the part I'm not understanding.

What's the next step? It seems like Google will send a response to the callbackURL we provide. But in that case, when does the callback to passport.use run? That callback is accepting accessToken, refreshToken,  and profile, so it seems like it is the one receiving the response from Google, not the callbackURL.

答:
In your application, when a user gives you permission to authenticate their account via Google for the first time, two possible 'flows' to consider:

user already has an existing account in your system and would like to link that account to her Google identity.

user is creating a new account in your system and you provide her with an option to create a new account using her Google identity

The end result if the user opts to authenticate using Google is a record in your database containing additional information provided from Google's auth service response. The data looks something similar to this page in passport docs.

The passport.use(...) call with the first argument of an object with your tokens is what passport uses to access Google's system (standard OAUTH2 credentials). The second argument is the callback function that interacts with your system's data layer, ex: User.findOrCreate(data).

On future visits to your application, a user can take advantage of the fact that their account is 'connected' with their Google identity and have a simple sign-in experience.

Body:
I'm using Passport and working on the Google OAuth 2 strategy. I'm having trouble understanding the flow.

Here is the code in the official docs:

var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://www.example.com/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, done) {
       User.findOrCreate({ googleId: profile.id }, function (err, user) {
         return done(err, user);
       });
  }
));

And then this for the routes:

// GET /auth/google
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Google authentication will involve
//   redirecting the user to google.com.  After authorization, Google
//   will redirect the user back to this application at /auth/google/callback
app.get('/auth/google',
  passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

// GET /auth/google/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Here's my understanding of the flow. User clicks a button to log in with google on the browser. Request is sent to /auth/google. Which calls passport.authenticate. From there, Google handles some stuff and once the user gives us permission to access their Google account, well, that's the part I'm not understanding.

What's the next step? It seems like Google will send a response to the callbackURL we provide. But in that case, when does the callback to passport.use run? That callback is accepting accessToken, refreshToken,  and profile, so it seems like it is the one receiving the response from Google, not the callbackURL.


问:
Extracting data from one text file to another using a batch file
Recently I've been having problems with my internet connection. In order to find the problem in the chain I looked into some code I found online. I have never written code for a batch-file before, so just go ahead and expect me to know barrely anything. Anyway, I played around with it a bit and found out what each of the lines does.. to an extend at least. Now the results I'm getting from that file are included below as well. What I want to do is write a seperate file which I can run that takes the results from the first file and filters them into a new textfile.

I've already dug through some of the examples I've found here, but I don't simply want to copy paste (not that such a solution would work... I tried so I could reverse engineer it, but to no avail). I found some examples of how to get data from a file using a FOR and a FOREACH-Object, but it makes very little sense to me and I can't get it to work.

In short, I would like the pinging data that's placed in the first text file to be filtered by a batch file so it only sends part of the text to the new text file. Is anything like this possible and if so how do I go about this? Some explanation about how it works would be great as I like to take code apart and play around with it.

The code I use to get the pinging data whenever a connection fault is detected is listed below. I'm not saying it works perfectly mainly because I'm not 100% on how the %SystemRoot%-part works... But so far every time it triggers it also finds a request timeout. I'm open for suggestions to improve this but I would like for the focus to be on the noted challenge of extracting from one file and sending it to another.

```<code>:Loop
::Starting up the loop

PING -n 5 127.0.0.1 > NUL
::Set the ping delay

set Address=google.com
::Set the address to ping to google.com

%SystemRoot%\system32\ping.exe -n 1 %Address%|%SystemRoot%\system32\find.exe "TTL=" > NUL
::Check the connection

if %ERRORLEVEL% EQU 0 goto Loop
::If no error, return to Loop
::So if error, continue to next statement

echo Pinging %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging action

echo Trace route %Address% at %date% %time% >>
D:\pingtest\Test\logfiletest.log
::Echo the route to trace and the timestamp

tracert %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging and results

echo. >> D:\pingtest\Test\logfiletest.log
::Nextline

goto Loop
::Return to Loop
</code>```

These are the results I'm getting that I'm trying to filter into the new file.

```<code>Pinging google.com
Trace route google.com at Fri 05/24/2019 10:22:40.92
Tracing route to google.com [172.217.168.238]

over a maximum of 30 hops:
1    <1 ms    <1 ms    <1 ms  MyLocation
2    13 ms    12 ms    13 ms  195.190.228.150
3     *        *        *     Request timed out.
4     7 ms    10 ms     8 ms  139.156.127.75
5     7 ms     8 ms     9 ms  108.170.241.193
6    15 ms    18 ms    17 ms  72.14.238.245
7     8 ms     7 ms     7 ms  ams16s31-in-f14.1e100.net [172.217.19.206]

Trace complete.
</code>```

So that is the result I am currently getting from the batch-file that I made after looking at the suggested code for another issue. Now what I would like to see something along the lines of the following

```<code>Trace route google.com at Fri 05/24/2019 10:22:40.92
3     *        *        *     Request timed out.
5     7 ms     8 ms     9 ms  108.170.241.193
</code>```

I'm taking rows 3 and 5 as examples because they often return a 'Request timed out'

答:
Pipe tracert to find.

Change this line

```<code>tracert %Address% >> D:\pingtest\Test\logfiletest.log
</code>```

to

```<code>tracert %Address% | find "Request timed out." >> D:\pingtest\Test\logfiletest.log
</code>```

find searches for lines containing Request timed out. and will output those lines.

View find /? for help.

If you want to understand the other commands,
view command /? where command represents
the command that you want help with.

Also view Using command redirection operators

Body:
Recently I've been having problems with my internet connection. In order to find the problem in the chain I looked into some code I found online. I have never written code for a batch-file before, so just go ahead and expect me to know barrely anything. Anyway, I played around with it a bit and found out what each of the lines does.. to an extend at least. Now the results I'm getting from that file are included below as well. What I want to do is write a seperate file which I can run that takes the results from the first file and filters them into a new textfile.

I've already dug through some of the examples I've found here, but I don't simply want to copy paste (not that such a solution would work... I tried so I could reverse engineer it, but to no avail). I found some examples of how to get data from a file using a FOR and a FOREACH-Object, but it makes very little sense to me and I can't get it to work.

In short, I would like the pinging data that's placed in the first text file to be filtered by a batch file so it only sends part of the text to the new text file. Is anything like this possible and if so how do I go about this? Some explanation about how it works would be great as I like to take code apart and play around with it.

The code I use to get the pinging data whenever a connection fault is detected is listed below. I'm not saying it works perfectly mainly because I'm not 100% on how the %SystemRoot%-part works... But so far every time it triggers it also finds a request timeout. I'm open for suggestions to improve this but I would like for the focus to be on the noted challenge of extracting from one file and sending it to another.

:Loop
::Starting up the loop

PING -n 5 127.0.0.1 > NUL
::Set the ping delay

set Address=google.com
::Set the address to ping to google.com

%SystemRoot%\system32\ping.exe -n 1 %Address%|%SystemRoot%\system32\find.exe "TTL=" > NUL
::Check the connection

if %ERRORLEVEL% EQU 0 goto Loop
::If no error, return to Loop
::So if error, continue to next statement

echo Pinging %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging action

echo Trace route %Address% at %date% %time% >>
D:\pingtest\Test\logfiletest.log
::Echo the route to trace and the timestamp

tracert %Address% >> D:\pingtest\Test\logfiletest.log
::Echo the pinging and results

echo. >> D:\pingtest\Test\logfiletest.log
::Nextline

goto Loop
::Return to Loop

These are the results I'm getting that I'm trying to filter into the new file.

Pinging google.com
Trace route google.com at Fri 05/24/2019 10:22:40.92
Tracing route to google.com [172.217.168.238]

over a maximum of 30 hops:
1    <1 ms    <1 ms    <1 ms  MyLocation
2    13 ms    12 ms    13 ms  195.190.228.150
3     *        *        *     Request timed out.
4     7 ms    10 ms     8 ms  139.156.127.75
5     7 ms     8 ms     9 ms  108.170.241.193
6    15 ms    18 ms    17 ms  72.14.238.245
7     8 ms     7 ms     7 ms  ams16s31-in-f14.1e100.net [172.217.19.206]

Trace complete.

So that is the result I am currently getting from the batch-file that I made after looking at the suggested code for another issue. Now what I would like to see something along the lines of the following

Trace route google.com at Fri 05/24/2019 10:22:40.92
3     *        *        *     Request timed out.
5     7 ms     8 ms     9 ms  108.170.241.193

I'm taking rows 3 and 5 as examples because they often return a 'Request timed out'

Body:
Pipe tracert to find.

Change this line

tracert %Address% >> D:\pingtest\Test\logfiletest.log

to

tracert %Address% | find "Request timed out." >> D:\pingtest\Test\logfiletest.log

find searches for lines containing Request timed out. and will output those lines.

View find /? for help.

If you want to understand the other commands,
view command /? where command represents
the command that you want help with.

Also view Using command redirection operators


问:
how to turn a list of strings into an object?
It's literally my second day on python so if this involve complex stuff like metaclasses just tell me, so I can come back to it when I'll be more experienced.
I'm trying to convert strings in objects and I think I almost got it, everything is detailed in the code section.

```<code>mike carpenter miami
jon driver roma
erika student london

# here's my text file, is a list of strings
</code>```

p = []

with open('people.txt', 'r') as text:
    for line in text:
        values = line.split(' ')
        p.append((values[0], values[1], values[2]))

#this converts each string in the text file in a list of strings with
# substrings becoming strings, all is put in a tuple named p

class person:
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

#this is my class, pretty self-explanatory
#now I can create objects like this:

person_number_0 = person(p[0][0], p[0][1], p[0][2])

#I can create objects using the tuple, but I don't want to do it manually
#for every different index, so I was thinking about a for-loop

n = 0
for line in p:
    obj = person(p[n][0], p[n][1], p[n][2])
    n = n + 1
#but I don't know how to create a new obj's name for every index

```

<p>Also if I run </p>

```print(obj.name)
```

<p>it gives me Mike, shouldn't it be Erika because at the end of the for-loop </p>

```obj = person(p[2][0], p[2][1], p[2][2])
```

or is not?

If it is something too complicated I'll back off, don't destroy me pls. Thanks everybody for any help or lessons.

答:
Code:

```<code># ignore this part it is the same as your code to read from the file
persons = [x.split() for x in """
    mike carpenter miami
    jon driver roma
    erika student london
""".split('\n')[1:-1]]

class Person:
    # this converts each string in the text file in a list of strings with
    # substrings becoming strings, all is put in a tuple named p
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

    def __str__(self):
        # this allows showing the class as a string (str)
        return "name: {}  job: {}  loc: {}".format(
            self.name, self.job, self.location)

for p in persons:
    print(Person(p[0], p[1], p[2]))
</code>```

Results:

```<code>name: mike  job: carpenter  loc: miami
name: jon  job: driver  loc: roma
name: erika  job: student  loc: london
</code>```

Body:
It's literally my second day on python so if this involve complex stuff like metaclasses just tell me, so I can come back to it when I'll be more experienced.
I'm trying to convert strings in objects and I think I almost got it, everything is detailed in the code section.

mike carpenter miami
jon driver roma
erika student london

# here's my text file, is a list of strings

p = []

with open('people.txt', 'r') as text:
    for line in text:
        values = line.split(' ')
        p.append((values[0], values[1], values[2]))

#this converts each string in the text file in a list of strings with
# substrings becoming strings, all is put in a tuple named p

class person:
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

#this is my class, pretty self-explanatory
#now I can create objects like this:

person_number_0 = person(p[0][0], p[0][1], p[0][2])

#I can create objects using the tuple, but I don't want to do it manually
#for every different index, so I was thinking about a for-loop

n = 0
for line in p:
    obj = person(p[n][0], p[n][1], p[n][2])
    n = n + 1
#but I don't know how to create a new obj's name for every index

Also if I run

print(obj.name)

it gives me Mike, shouldn't it be Erika because at the end of the for-loop

obj = person(p[2][0], p[2][1], p[2][2])

or is not?

If it is something too complicated I'll back off, don't destroy me pls. Thanks everybody for any help or lessons.

Body:
Code:

# ignore this part it is the same as your code to read from the file
persons = [x.split() for x in """
    mike carpenter miami
    jon driver roma
    erika student london
""".split('\n')[1:-1]]

class Person:
    # this converts each string in the text file in a list of strings with
    # substrings becoming strings, all is put in a tuple named p
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

    def __str__(self):
        # this allows showing the class as a string (str)
        return "name: {}  job: {}  loc: {}".format(
            self.name, self.job, self.location)

for p in persons:
    print(Person(p[0], p[1], p[2]))

Results:

name: mike  job: carpenter  loc: miami
name: jon  job: driver  loc: roma
name: erika  job: student  loc: london


问:
How to replace Sql Server with Sqlite in Aspnetboilerplate?
I am trying to replace sql server with sqlite as database in aspnetboilerplate following this tutorial. we have to remove previous migrations and add new one before running "update-database" but it gives empty database and running this project gives error " 'SQLite Error 1: 'no such table: AbpEditions". how to populate newly installed sqlite database?

there are SeedHelper.cs and initialHostDbBuilder.cs files in EntityFrameworkCore project, probably for seeding database but i could not figure out how to use them?

答:
Make sure that config files in all of your projects that need the access to the database are pointing to the same file. If you have just used the value from the article

```<code>    "Default": "Data Source=SqliteDemoDb.db"
</code>```

then you have a separate database file in each project. The file that the migrations are executed on is in the EntityFramework project.

Body:
Make sure that config files in all of your projects that need the access to the database are pointing to the same file. If you have just used the value from the article

    "Default": "Data Source=SqliteDemoDb.db"

then you have a separate database file in each project. The file that the migrations are executed on is in the EntityFramework project.


问:
Which shall I convert a byte stream first, buffer stream or char stream?
To get a buffered char stream for a given byte stream, which shall I convert the byte stream to first, a buffer stream or a char stream?

Given an OutputStream object os (such as FileOutputStream
object or System.out), there seems to be two ways to get a
buffered char stream:

```<code>new BufferedWriter(new OutputStreamWriter(os));

new OutputStreamWriter(new BufferedOutputStream(os));
</code>```

What differences are between them?

Given an InputStream object is (such as FileInputStream object
or System.in), there seems to be two ways to get a buffered char
stream:

```<code>new BufferedReader(new InputStreamReader(is));

new InputStreamReader(new BufferedInputStream(is));
</code>```

What differences are between them?

答:
As stated in javadoc for OutputStreamWriter

The characters passed to the write() methods are not buffered.

  For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations.  For example:

  Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

Since resulting bytes after conversion are accumulated in a buffer, there is no need to in-pipe BufferedStream after OutputStreamWriter

Thus, the conventional way is to use:

```<code>new BufferedWriter(new OutputStreamWriter(os));
</code>```

Similar reason for InputStreamReader

Use:

```<code>new BufferedReader(new InputStreamReader(is));
</code>```

Body:
To get a buffered char stream for a given byte stream, which shall I convert the byte stream to first, a buffer stream or a char stream?

Given an OutputStream object os (such as FileOutputStream
object or System.out), there seems to be two ways to get a
buffered char stream:

new BufferedWriter(new OutputStreamWriter(os));

new OutputStreamWriter(new BufferedOutputStream(os));

What differences are between them?

Given an InputStream object is (such as FileInputStream object
or System.in), there seems to be two ways to get a buffered char
stream:

new BufferedReader(new InputStreamReader(is));

new InputStreamReader(new BufferedInputStream(is));

What differences are between them?

Body:
As stated in javadoc for OutputStreamWriter

The characters passed to the write() methods are not buffered.

  For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations.  For example:

  Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

Since resulting bytes after conversion are accumulated in a buffer, there is no need to in-pipe BufferedStream after OutputStreamWriter

Thus, the conventional way is to use:

new BufferedWriter(new OutputStreamWriter(os));

Similar reason for InputStreamReader

Use:

new BufferedReader(new InputStreamReader(is));


问:
Random Character in map in DynamoDB
When I update some record in DynamoDB as such

```<code>UpdateExpression: "set #audioField = :payload",
ExpressionAttributeValues: {
              ":payload": something,
          },

var something = {"test.com1": {}}
</code>```

DynamoDB puts a random character in the record like this

```<code>{ "test.com1" : { "M" : { } }}
</code>```

What's up with this? And how do I prevent this?

答:
This is not a random character, this is how DynamoDB stores and represents types.

DynamoDB embeds type information in each value that is stores.  See the following for the list of types: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html

Based on the linked above, The "M" that you are seeing is describing the contents of "test.com1" attribute which is a map (M for map).

The reason you are not seeing these in your other attributes is probably because the SDK is automatically translating this DynamoDB structure into native types for the top-level attributes but not for nested attributes.

What language/SDK are you using?  Many SDKs have helpers that you can pass your results through to parse these embedded types and convert them into native types that are easier to work with.

Title: Random Character in map in DynamoDB

Body:
When I update some record in DynamoDB as such

UpdateExpression: "set #audioField = :payload",
ExpressionAttributeValues: {
              ":payload": something,
          },

var something = {"test.com1": {}}

DynamoDB puts a random character in the record like this

{ "test.com1" : { "M" : { } }}

What's up with this? And how do I prevent this?


问:
Grep to identify flles in a directory that contain all zeros and list or delete them
Have numerous image files in a directory that have been corrupted and contain only zero hex value (although some are very large)- among other images that are not corrupt.Want to search through the directory identify files that contain only zeros and delete them.

I am running this from terminal on a mac.

I am thinking grep, recursive, stop searching and eliminate from deletion any file if it contains a value other than zeros, delete zero value files with rm. However- I am a novice and do not know how to put it together.

Or have the zero files moved to a directory from which I can delete them (want to be careful not to delete any good image files.)

答:
To test if a file named $fname contains only hex zeros, try:

```<code>head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname"
</code>```

Here, head -c "$(wc -c <"$fname")" /dev/zero creates a string of zero bytes exactly as long as the file $fname.  cmp -s - "$fname" compares that string of hex zeros to the file itself.  If they match, then cmp sets its exit code to success (0).

To list all regular files in a directory which contain only hex zeros:

```<code>for fname in ./*
do
   [ -f "$fname" ] && head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname" && echo "$fname"
done
</code>```

To delete all regular files in a directory which contain only hex zeros, we just replace echo with rm:

```<code>for fname in ./*
do
   [ -f "$fname" ] && head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname" && rm "$fname"
done
</code>```

Here, [ -f "$fname" ] tests to see if the file is a regular file, not a directory. head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname" tests to see if the file has only hex zeros in it.  If cmp retursn success, rm "$fname" deletes that file.

Body:
To test if a file named $fname contains only hex zeros, try:

head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname"

Here, head -c "$(wc -c <"$fname")" /dev/zero creates a string of zero bytes exactly as long as the file $fname.  cmp -s - "$fname" compares that string of hex zeros to the file itself.  If they match, then cmp sets its exit code to success (0).

To list all regular files in a directory which contain only hex zeros:

for fname in ./*
do
   [ -f "$fname" ] && head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname" && echo "$fname"
done

To delete all regular files in a directory which contain only hex zeros, we just replace echo with rm:

for fname in ./*
do
   [ -f "$fname" ] && head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname" && rm "$fname"
done

Here, [ -f "$fname" ] tests to see if the file is a regular file, not a directory. head -c "$(wc -c <"$fname")" /dev/zero | cmp -s - "$fname" tests to see if the file has only hex zeros in it.  If cmp retursn success, rm "$fname" deletes that file.


问:
SQLSTATE[HY000] [2002] Connection refused (SQL: insert into users(name,email) values(mahmud,mahmudul@gamil.com))
I am using MySql Workbench for database. All doing well when I migrate my project.But when I want to insert data to the users table that time occurs this error "SQLSTATE[HY000] [2002] Connection refused (SQL: insert into users(name,email) values(mahmud,mahmudul@gamil.com))"

I am using windows, laravel 5.8,Homestead, MySql Workbench.

here some file:

.env:
enter image description here

```<code>APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:KRf7nQxvFaheTWWPsflVa4KYZXR5Jwo5IvwXxogDJn4=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=33060
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

</code>```

database.php:
enter image description here

```<code> 'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '33060'),
            'database' => env('DB_DATABASE', 'homestead'),
            'username' => env('DB_USERNAME', 'homestead'),
            'password' => env('DB_PASSWORD', 'secret'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]
</code>```

web.php:
enter image description here

```<code>Route::get('/', function () {
    return view('welcome');
});

Route::get('/insert',function(){
    DB::insert("insert into users(name,email) values(?,?)",["mahmud","mahmudul@gamil.com"]);
});

</code>```

page like:
enter image description here

please help me how to solve it.

thanks advance.

答:
change .env and database.php:

.env:

replace

```<code>DB_HOST = 127.0.0.1
</code>```

to

```<code>DB_HOST = localhost
</code>```

and

database.php:

replace

```<code>'host' => env('DB_HOST', '127.0.0.1')
</code>```

to

```<code>'host' => env('DB_HOST', 'localhost')
</code>```

note: MySql Connection Hostname will be 127.0.0.1 and port will be 33060:

Body:
I am using MySql Workbench for database. All doing well when I migrate my project.But when I want to insert data to the users table that time occurs this error "SQLSTATE[HY000] [2002] Connection refused (SQL: insert into users(name,email) values(mahmud,mahmudul@gamil.com))"

I am using windows, laravel 5.8,Homestead, MySql Workbench.

here some file:

.env:
enter image description here

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:KRf7nQxvFaheTWWPsflVa4KYZXR5Jwo5IvwXxogDJn4=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=33060
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

database.php:
enter image description here

 'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '33060'),
            'database' => env('DB_DATABASE', 'homestead'),
            'username' => env('DB_USERNAME', 'homestead'),
            'password' => env('DB_PASSWORD', 'secret'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]

web.php:
enter image description here

Route::get('/', function () {
    return view('welcome');
});

Route::get('/insert',function(){
    DB::insert("insert into users(name,email) values(?,?)",["mahmud","mahmudul@gamil.com"]);
});

page like:
enter image description here

please help me how to solve it.

thanks advance.

Body:
change .env and database.php:

.env:

replace

DB_HOST = 127.0.0.1

to

DB_HOST = localhost

and

database.php:

replace

'host' => env('DB_HOST', '127.0.0.1')

to

'host' => env('DB_HOST', 'localhost')

note: MySql Connection Hostname will be 127.0.0.1 and port will be 33060:


问:
Is there a way to filter network requests using Google Chrome developer tools?
Is it possible to filter out some requests using Chrome developer tools, say, filter out all image requests?</p>

答:
Under my build of Google Chrome (Version 74.0.3729.157 (64-bit)), I've found the following filters available (I've added some examples). Note that DevTools has an AutoComplete functionality (which helps a lot in sorting this stuff out).</p>

```<code>domain:
-domain:
    # Use a * character to include multiple domains.
    # Ex:  *.com, domain:google.com, -domain:bing.com

has-response-header:
-has-response-header:
    # Filter resources with the specified HTTP response header.
    # Ex: has-response-header:Content-Type, has-response-header:age

is:
-is:
    # is:running finds WebSocket resources
    # I've also come across:
    #  - is:from-cache,
    #  - is:service-worker-initiated
    #  - is:service-worker-intercepted

larger-than:
-larger-than:
    # Note: larger-than:1000 is equivalent to larger-than:1k
    # Ex: larger-than:420, larger-than:4k, larger-than:100M

method:
-method:
    # method:POST, -method:OPTIONS, method:PUT, method:GET

mime-type:
-mime-type:
    # Ex: mime-type:application/manifest+json, mimetype:image/x-icon

mixed-content:
-mixed-content:
    # 2 that I've found documented:
    #   mixed-content:all (Show all mixed-content resources)
    #   mixed-content:displayed (Show only those currently displayed) (never used this personally)

scheme:
-scheme:
    # Ex: scheme:http, scheme:https,
    # Note that there are also scheme:chrome-extension, scheme:data

set-cookie-domain:
-set-cookie-domain:
    #
    # Ex: set-cookie-domain:.google.com

set-cookie-name:
-set-cookie-name:
    # Match Set-Cookie response headers with name
    # Ex: set-cookie-name:WHATUP

set-cookie-value:
-set-cookie-value:
    # Match Set-Cookie response headers with value
    # Ex: set-cookie-value:AISJHD98ashfa93q2rj_94w-asd-yolololo

status-code:
-status-code:
    # Match HTTP status code
    # Ex: status-code:200, -status-code:302
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Under my build of Google Chrome (Version 74.0.3729.157 (64-bit)), I've found the following filters available (I've added some examples). Note that DevTools has an AutoComplete functionality (which helps a lot in sorting this stuff out).

domain:
-domain:
    # Use a * character to include multiple domains.
    # Ex:  *.com, domain:google.com, -domain:bing.com

has-response-header:
-has-response-header:
    # Filter resources with the specified HTTP response header.
    # Ex: has-response-header:Content-Type, has-response-header:age

is:
-is:
    # is:running finds WebSocket resources
    # I've also come across:
    #  - is:from-cache,
    #  - is:service-worker-initiated
    #  - is:service-worker-intercepted

larger-than:
-larger-than:
    # Note: larger-than:1000 is equivalent to larger-than:1k
    # Ex: larger-than:420, larger-than:4k, larger-than:100M

method:
-method:
    # method:POST, -method:OPTIONS, method:PUT, method:GET

mime-type:
-mime-type:
    # Ex: mime-type:application/manifest+json, mimetype:image/x-icon

mixed-content:
-mixed-content:
    # 2 that I've found documented:
    #   mixed-content:all (Show all mixed-content resources)
    #   mixed-content:displayed (Show only those currently displayed) (never used this personally)

scheme:
-scheme:
    # Ex: scheme:http, scheme:https,
    # Note that there are also scheme:chrome-extension, scheme:data

set-cookie-domain:
-set-cookie-domain:
    #
    # Ex: set-cookie-domain:.google.com

set-cookie-name:
-set-cookie-name:
    # Match Set-Cookie response headers with name
    # Ex: set-cookie-name:WHATUP

set-cookie-value:
-set-cookie-value:
    # Match Set-Cookie response headers with value
    # Ex: set-cookie-value:AISJHD98ashfa93q2rj_94w-asd-yolololo

status-code:
-status-code:
    # Match HTTP status code
    # Ex: status-code:200, -status-code:302


答:
Having defined your class as you have, then simply read the file as something like:

```<code>with open('people.txt', 'r') as f:
    people = [person(*line.split()) for line in f]
</code>```

Now you could see the contents as:

```<code>for p in people:
    print(p.name, p.job, p.location)
</code>```

Title: how to turn a list of strings into an object?

Body:
Having defined your class as you have, then simply read the file as something like:

with open('people.txt', 'r') as f:
    people = [person(*line.split()) for line in f]

Now you could see the contents as:

for p in people:
    print(p.name, p.job, p.location)


问:
Laravel Method notify does not exist
I am trying to notify user if a new form is inserted to database, but I get this error:

```<code>BadMethodCallException in Macroable.php line 74: Method notify does not exist.
</code>```

This is the notification class

```<code><?php

namespace App\Notifications\Admin;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

use App\Models\Admin\Forms\Prescriptions;

class PrescriptionNotification extends Notification
{
    use Queueable;

    public $Prescription;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Prescriptions $Prescription)
    {
        $this->Prescriptions = $Prescription;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $url = url('/admin/prescriptions/edit/'.$this->Prescriptions->id);

        return (new MailMessage)
                    ->line('New form')
                    ->action('View', $url)
                    ->line('');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'test' => 'test'
        ];
    }
}
</code>```

And in my controller I am doing this:

```<code> $users = App\User::all()->where('role', 3);
 //trigger email notification
 $Prescription = Prescriptions::first();
 $users->notify(new PrescriptionNotification($Prescription));
</code>```

Been following This tutorial, but still to no avail. I have Notifiable in the user model. What else can be done? I am losing my mind what causes this error.

As requested my User class:

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    //is admin
    public function isAdmin()
    {
        return $this->role; // this looks for an admin column in your users table
    }

    //relationship with prescription forms
    public function confirmations()
    {
        return $this->hasMany('App\Models\Admin\Forms\Prescription_confirmations', 'physician_id');
    }

    //relationship with prescriptions forms
    public function prescriptions()
    {
        return $this->hasMany('App\Models\Admin\Forms\Prescriptions', 'physician_id');
    }
}
</code>```

答:
Also, you can use higher-order messages:</p>

```<code>$users->each->notify(new PrescriptionNotification($Prescription));
</code>```

Title: Laravel Method notify does not exist

Body:
I am trying to notify user if a new form is inserted to database, but I get this error:

BadMethodCallException in Macroable.php line 74: Method notify does not exist.

This is the notification class

<?php

namespace App\Notifications\Admin;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

use App\Models\Admin\Forms\Prescriptions;

class PrescriptionNotification extends Notification
{
    use Queueable;

    public $Prescription;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Prescriptions $Prescription)
    {
        $this->Prescriptions = $Prescription;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $url = url('/admin/prescriptions/edit/'.$this->Prescriptions->id);

        return (new MailMessage)
                    ->line('New form')
                    ->action('View', $url)
                    ->line('');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'test' => 'test'
        ];
    }
}

And in my controller I am doing this:

 $users = App\User::all()->where('role', 3);
 //trigger email notification
 $Prescription = Prescriptions::first();
 $users->notify(new PrescriptionNotification($Prescription));

Been following This tutorial, but still to no avail. I have Notifiable in the user model. What else can be done? I am losing my mind what causes this error.

As requested my User class:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    //is admin
    public function isAdmin()
    {
        return $this->role; // this looks for an admin column in your users table
    }

    //relationship with prescription forms
    public function confirmations()
    {
        return $this->hasMany('App\Models\Admin\Forms\Prescription_confirmations', 'physician_id');
    }

    //relationship with prescriptions forms
    public function prescriptions()
    {
        return $this->hasMany('App\Models\Admin\Forms\Prescriptions', 'physician_id');
    }
}

Body:
Also, you can use higher-order messages:

$users->each->notify(new PrescriptionNotification($Prescription));


问:
c++ set_intersection having different results with same input
I've been trying to get the intersection of two sets, but for some reason it keeps having different results with the same inputs. The std::set_intersect receives the iterators to two sets (connBuilds, connectedSection): The first has 5 values and the second has 4.
Here are the values of the sets (containing pointers to a class):

Set 1 :

Set 2 :

The expected result would be a set containing the 4 common values between the sets, but the result varies with each execution. Sometimes, the result is correct, sometimes it isn't.

Here's the code segment where the intersection is done:

std::vector<Building *> v;
bool hasHC = false;
bool hasH = false;

ConnectedBuildings connBuilds = invertedBuildingsItr->second;
std::set_intersection(connectedSection.begin(), connectedSection.end(), connBuilds.begin(),
                              connBuilds.end(), std::back_inserter(v));
size_t currentSize = v.size();
```

<p>Here's the struct used for comparing the pointers:</p>

<pre class="lang-cpp prettyprint-override"><code>struct buildingPTRComp
{
    bool operator()(Building *b1, Building *b2) const
    {
        return b1->getIdentifier() < b2->getIdentifier();
    }

};

typedef std::set<Building *, buildingPTRComp> ConnectedBuildings;

</code>```

答:
std::set_intersection is unaware of your comparison function, you are specifying your comparator for the set but most of <algorithm> functions are just working on iterators as intended.

You should pass your comparator to the function itself too using the proper overload:

```<code>template< class InputIt1, class InputIt2,
          class OutputIt, class Compare >
OutputIt set_intersection( InputIt1 first1, InputIt1 last1,
                           InputIt2 first2, InputIt2 last2,
                           OutputIt d_first, Compare comp );
</code>```

Body:
I've been trying to get the intersection of two sets, but for some reason it keeps having different results with the same inputs. The std::set_intersect receives the iterators to two sets (connBuilds, connectedSection): The first has 5 values and the second has 4.
Here are the values of the sets (containing pointers to a class):

Set 1 :

Set 2 :

The expected result would be a set containing the 4 common values between the sets, but the result varies with each execution. Sometimes, the result is correct, sometimes it isn't.

Here's the code segment where the intersection is done:

std::vector<Building *> v;
bool hasHC = false;
bool hasH = false;

ConnectedBuildings connBuilds = invertedBuildingsItr->second;
std::set_intersection(connectedSection.begin(), connectedSection.end(), connBuilds.begin(),
                              connBuilds.end(), std::back_inserter(v));
size_t currentSize = v.size();

Here's the struct used for comparing the pointers:

struct buildingPTRComp
{
    bool operator()(Building *b1, Building *b2) const
    {
        return b1->getIdentifier() < b2->getIdentifier();
    }

};

typedef std::set<Building *, buildingPTRComp> ConnectedBuildings;

Body:
std::set_intersection is unaware of your comparison function, you are specifying your comparator for the set but most of <algorithm> functions are just working on iterators as intended.

You should pass your comparator to the function itself too using the proper overload:

template< class InputIt1, class InputIt2,
          class OutputIt, class Compare >
OutputIt set_intersection( InputIt1 first1, InputIt1 last1,
                           InputIt2 first2, InputIt2 last2,
                           OutputIt d_first, Compare comp );


问:
How to access individual strings in Python?
I am trying to access two strings which are coupled together. I do not know how to access them individually, as subscription does not work.

I tried printing the variable b in the following example, and I get two strings. However using b[0] does not give me the first string separately.

```<code>import numpy as np
import json
import requests
from datetime import datetime

resp = requests.get("https://api.mfapi.in/mf/130503")
data = resp.json()

x = data['data']

for i in range(1):
    for a,b in x[i].items():
        print(b)
</code>```

答: It's because in your loop i starts and stops at 1. You can access the first one trough x[0]['date'] and x[0]['nav']

Body:
I am trying to access two strings which are coupled together. I do not know how to access them individually, as subscription does not work.

I tried printing the variable b in the following example, and I get two strings. However using b[0] does not give me the first string separately.

import numpy as np
import json
import requests
from datetime import datetime

resp = requests.get("https://api.mfapi.in/mf/130503")
data = resp.json()

x = data['data']

for i in range(1):
    for a,b in x[i].items():
        print(b)


问:
UIWebView loading
I want load the html data in webview. At the button click, it open the viewcontroller and load the html data in this viewcontroller (add web view in this view controller using Interface builder). When the html data not proper loading and i press the back button, at that time crash the app. i am not doing allocation & init webview in the coding. set IBOUTLET using Interface builder & bind it.

```<code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [connection release];
    NSString *strResponce = [[NSString alloc] initWithData:jsonData_Info encoding:NSUTF8StringEncoding];
    [jsonData_Info release];
    NSError *error;
    SBJSON *json = [[SBJSON new] autorelease];
    self.jsonArray_Info=[json objectWithString:strResponce error:&error];
    str_InfoDetail = [[self.jsonArray_Info objectAtIndex:0] valueForKey:@"Page"];
    str_html = [NSString stringWithFormat:@"%@",str_InfoDetail];
    NSString *temp;
    temp = [NSString stringWithFormat:@"<html><head><style>body{background-color:transparent;}</style></head><body><span style='color:white'>%@</span></body></html>",str_html];
    //web_Information = [[UIWebView alloc]init];
    web_Information.backgroundColor=[UIColor clearColor];
    web_Information.opaque= NO;

    [web_Information loadHTMLString:temp baseURL:nil];
    [act stopAnimating];
    [strResponce release];
}
</code>```

please give me any solution.

thanks.

答: Pls post some code and crash log if you need answers. By the look of it I think it may be because of implementation of UIWebView delegate in your class. I think when you navigate back you do not make the delegate nil which can cause the app to crash

Title: UIWebView loading

Body:
I want load the html data in webview. At the button click, it open the viewcontroller and load the html data in this viewcontroller (add web view in this view controller using Interface builder). When the html data not proper loading and i press the back button, at that time crash the app. i am not doing allocation & init webview in the coding. set IBOUTLET using Interface builder & bind it.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [connection release];
    NSString *strResponce = [[NSString alloc] initWithData:jsonData_Info encoding:NSUTF8StringEncoding];
    [jsonData_Info release];
    NSError *error;
    SBJSON *json = [[SBJSON new] autorelease];
    self.jsonArray_Info=[json objectWithString:strResponce error:&error];
    str_InfoDetail = [[self.jsonArray_Info objectAtIndex:0] valueForKey:@"Page"];
    str_html = [NSString stringWithFormat:@"%@",str_InfoDetail];
    NSString *temp;
    temp = [NSString stringWithFormat:@"%@",str_html];
    //web_Information = [[UIWebView alloc]init];
    web_Information.backgroundColor=[UIColor clearColor];
    web_Information.opaque= NO;

    [web_Information loadHTMLString:temp baseURL:nil];
    [act stopAnimating];
    [strResponce release];
}

please give me any solution.

thanks.


问:
How to find fontAwsome icon's name
I'm trying to use font-awesome icons in a react native app, therefore I installed it and imported it using react-native-vector-icons :

```<code>import Icon from "react-native-vector-icons/FontAwesome";
.....
<Icon name="map-pin" />
</code>```

however I don't know where to find the name of the icons, I browsed in the font awesome web site, found some icons, but when I tried to use them, it doesn't work
 for example in their website  this icon's name is  abacus, however, when I use it in my app, I get a warning and the icon doesn't display.

答: You can use https://oblador.github.io/react-native-vector-icons/ to find the icon names. It has all the icons in the react-native-vector-icons library.

Title: How to find fontAwsome icon's name

Body:
I'm trying to use font-awesome icons in a react native app, therefore I installed it and imported it using react-native-vector-icons :

import Icon from "react-native-vector-icons/FontAwesome";
.....
<Icon name="map-pin" />

however I don't know where to find the name of the icons, I browsed in the font awesome web site, found some icons, but when I tried to use them, it doesn't work
 for example in their website  this icon's name is  abacus, however, when I use it in my app, I get a warning and the icon doesn't display.


问:
Find new, removed and same elements in a vector or collection compared to another
Considering you have two collections containing no duplicates:

```<code>std::vector<T*> previous;
std::vector<T*> current;
</code>```

Is there an elegant way to split these two collections into three collections containing the elements that are the same in both, the elements in current that were not in previous and the elements that were in previous that are not in current? Resulting in:

```<code>std::vector<T*> removed;
std::vector<T*> same;
std::vector<T*> inserted;
</code>```

Is there maybe a std:: function that does that?

EDIT:

The collections can be sorted but as they are collections of pointers by what metric but their address value?

The collections should not contain duplicates.

答: You can first find intersection (same vector) of current and previous using std::set_intersection. After that, it’s possible to find removed and inserted using std::set_difference by subtracting found intersection from previous and current correspondingly.

Body:
Considering you have two collections containing no duplicates:

std::vector<T*> previous;
std::vector<T*> current;

Is there an elegant way to split these two collections into three collections containing the elements that are the same in both, the elements in current that were not in previous and the elements that were in previous that are not in current? Resulting in:

std::vector<T*> removed;
std::vector<T*> same;
std::vector<T*> inserted;

Is there maybe a std:: function that does that?

EDIT:

The collections can be sorted but as they are collections of pointers by what metric but their address value?

The collections should not contain duplicates.


问:
Functions not firing in correct order with async / await
In an Angular service, I have created the following function:

```<code>getListKey(user) {
  firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
    console.log(snapshot.val())
    this.listKey = snapshot.val()
    return this.listKey
  })
}
</code>```

I want to call this function in another file on load, and assign the value brought back to a global listKey variable in the service to be used for another function from the component. However, the second function is firing before the data has been retrieved even with using async/await.

This is the relevant piece from my component:

```<code>this.afAuth.authState.subscribe(async (user: firebase.User) => {
  await this.fire.getListKey(user);
  this.fire.getUserList(this.fire.listKey).subscribe(lists => {...})
  ...
}
</code>```

How can I make getUserList() wait for listKey?

答:
Add a return statement to getListKey to return the promise. Otherwise, you're returning undefined, and awaiting undefined will not wait for the database snapshot to be ready.

```<code>getListKey(user) {
  return firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
    console.log(snapshot.val())
    this.listKey = snapshot.val()
    return this.listKey
  })
}
</code>```

Also, you probably want a left side to your await:

```<code>this.afAuth.authState.subscribe(async (user: firebase.User) => {
  const listKey = await this.fire.getListKey(user);
  this.fire.getUserList(listKey).subscribe(lists => {...})
  ...
}

</code>```

Body:
In an Angular service, I have created the following function:

getListKey(user) {
  firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
    console.log(snapshot.val())
    this.listKey = snapshot.val()
    return this.listKey
  })
}

I want to call this function in another file on load, and assign the value brought back to a global listKey variable in the service to be used for another function from the component. However, the second function is firing before the data has been retrieved even with using async/await.

This is the relevant piece from my component:

this.afAuth.authState.subscribe(async (user: firebase.User) => {
  await this.fire.getListKey(user);
  this.fire.getUserList(this.fire.listKey).subscribe(lists => {...})
  ...
}

How can I make getUserList() wait for listKey?

Body:
Add a return statement to getListKey to return the promise. Otherwise, you're returning undefined, and awaiting undefined will not wait for the database snapshot to be ready.

getListKey(user) {
  return firebase.database().ref(`userprofile/${user.uid}/list`).once('value').then(snapshot => {
    console.log(snapshot.val())
    this.listKey = snapshot.val()
    return this.listKey
  })
}

Also, you probably want a left side to your await:

this.afAuth.authState.subscribe(async (user: firebase.User) => {
  const listKey = await this.fire.getListKey(user);
  this.fire.getUserList(listKey).subscribe(lists => {...})
  ...
}