问:
How to drop rows by condition on string value in pandas dataframe?
Consider a Pandas Dataframe like:

```<code>>>> import pandas as pd
>>> df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com', 'http://www.url2.com','http://www.url3.com','http://www.url1.com']))
>>> df
</code>```

Giving:

```<code>                   url
0      http://url1.com
1  http://www.url1.com
2  http://www.url2.com
3  http://www.url3.com
4  http://www.url1.com
</code>```

I want to remove all rows containing url1.com and url2.com to obtain dataframe result like:

```<code>                   url
0   http://ww.url3.com
</code>```

I do this

```<code>domainToCheck = ('url1.com', 'url2.com')
goodUrl = df['url'].apply(lambda x : any(domain in x for domain in domainToCheck))
</code>```

But this give me no result.

Any idea how to solve the above problem?

Edit: Solution

```<code>import pandas as pd
import tldextract

df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com','http://www.url2.com','http://www.url3.com','http://www.url1.com']))
domainToCheck = ['url1', 'url2']
s = df.url.map(lambda x : tldextract.extract(x).domain).isin(domainToCheck)
df = df[~s].reset_index(drop=True)
</code>```

答:
If we checking domain , we should find the 100% match domain rather than use string contain . since the subdomain may contain the same key work as domain

```<code>import tldextract

s=df.url.map(lambda x : tldextract.extract(x).domain).isin(['url1','url2'])
Out[594]:
0     True
1     True
2     True
3    False
4     True
Name: url, dtype: bool

df=df[~s]
</code>```

Body:
Consider a Pandas Dataframe like:

>>> import pandas as pd
>>> df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com', 'http://www.url2.com','http://www.url3.com','http://www.url1.com']))
>>> df

Giving:

                   url
0      http://url1.com
1  http://www.url1.com
2  http://www.url2.com
3  http://www.url3.com
4  http://www.url1.com

I want to remove all rows containing url1.com and url2.com to obtain dataframe result like:

                   url
0   http://ww.url3.com

I do this

domainToCheck = ('url1.com', 'url2.com')
goodUrl = df['url'].apply(lambda x : any(domain in x for domain in domainToCheck))

But this give me no result.

Any idea how to solve the above problem?

Edit: Solution

import pandas as pd
import tldextract

df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com','http://www.url2.com','http://www.url3.com','http://www.url1.com']))
domainToCheck = ['url1', 'url2']
s = df.url.map(lambda x : tldextract.extract(x).domain).isin(domainToCheck)
df = df[~s].reset_index(drop=True)

Body:
If we checking domain , we should find the 100% match domain rather than use string contain . since the subdomain may contain the same key work as domain

import tldextract

s=df.url.map(lambda x : tldextract.extract(x).domain).isin(['url1','url2'])
Out[594]:
0     True
1     True
2     True
3    False
4     True
Name: url, dtype: bool

df=df[~s]


来源: stackexchange

问:
User can't select SVG in Episerver CMS (other image types are supported)
I am unable to get SVG images to show up in the "Select Image" box when a CMS user clicks the ellipse button for an image property on a page or block in Episerver. (Episerver 10.10.5.0)

The SVG images upload just fine, and they appear in the Assets Pane with the other images that have been uploaded. But when the user tries to select an image, only the other image types that are in the same folder appear.

I tried adding support via the model (Models\Media\VectorImageFile.cs) as suggested in the blog post here. When that didn't work, I removed VectorImageFile.cs and tried adding "svg" to the list of image extensions in Models\Media\ImageFile.cs:

```<code>[ContentType(DisplayName = "ImageFile", GUID = "88284fbf-9d34-469b-a259-716f8aac5529", Description = "")]
[MediaDescriptor(ExtensionString = "jpg,jpeg,jpe,ico,gif,bmp,png,svg")]
</code>```

Both of those attempts compiled without issue, but did not make SVG images available to the user when selecting an image file for an image property of a page or block.

Hope I've provided enough information. I'm an Episerver noob (and a C# noob, tbh). Any guidance will be gratefully appreciated!

答:
OK. Here are the answers I found to my question.

Put this code in a separate file, and make sure it's properly
referenced/included in the project.

Once it's there, you'll have a defined "VectorImageFile" type, but 1) users won't be able to upload SVG files anymore and 2) users still won't be able to select SVG images from a block editor with the UIHint.Image property set.

These guys documented issue/annoyance #1 above. Change the inheritance of "VectorImageFile" from ImageData to MediaData. Now users can upload SVG images again. But they still can't select them.

So, remove UIHint.Image from the property, allowing users to select whatever media or content type they want. Then, grab the ContentURL from the ContentReference, assign it to a string variable, and call that string variable as the src of an img tag in the View.

What. A. Pain.

ContentLicense: CC BY-SA 4.0

Body:
I am unable to get SVG images to show up in the "Select Image" box when a CMS user clicks the ellipse button for an image property on a page or block in Episerver. (Episerver 10.10.5.0)

The SVG images upload just fine, and they appear in the Assets Pane with the other images that have been uploaded. But when the user tries to select an image, only the other image types that are in the same folder appear.

I tried adding support via the model (Models\Media\VectorImageFile.cs) as suggested in the blog post here. When that didn't work, I removed VectorImageFile.cs and tried adding "svg" to the list of image extensions in Models\Media\ImageFile.cs:

[ContentType(DisplayName = "ImageFile", GUID = "88284fbf-9d34-469b-a259-716f8aac5529", Description = "")]
[MediaDescriptor(ExtensionString = "jpg,jpeg,jpe,ico,gif,bmp,png,svg")]

Both of those attempts compiled without issue, but did not make SVG images available to the user when selecting an image file for an image property of a page or block.

Hope I've provided enough information. I'm an Episerver noob (and a C# noob, tbh). Any guidance will be gratefully appreciated!


问:
How to change the color of a widget while it is pressed in flutter?
I have a Widget, and I want to change its background color while the user is pressing it, and when the pressing is finished, it returns to its original color.

I tried to use a GestureDetector, implementing onTapDown and onTapUp functions, but it doesn't work: it takes a long time (~150ms) to change color and, if I tap at normal speed, the color doesn't change.

I am an Android developer, and what I want to do is done in Android using a selector as follows:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="..." android:state_pressed="true" />
  <item android:drawable="..." />
</selector>.
</code>```

But I don't know how to do that with flutter. I hope the piece of code will help to understand what I want to achieve.

答:
Here is how I would do it:

```<code>
class MyWidget extends StatefulWidget {

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

class _MyWidgetState extends State<MyWidget> with SingleTickerProviderStateMixin {

  AnimationController _controller;
  Color myColor = Colors.blue;

  @override
  void initState() {
    _controller = AnimationController(vsync: this,duration: Duration(milliseconds: 400));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapUp: (_) {
        setState(() {
        myColor = Colors.blue;
        });
      },
      onTapDown: (_) {
        setState(() {
        myColor = Colors.red;
        });
      },
       child: AnimatedBuilder(animation: _controller,
       builder: (context, child) => Container(
         height: 200,
         width: 200,
         color : myColor,
       )),
    );
  }
}

</code>```

You can change the duration in the animationController if it's too slow.

Body:
I have a Widget, and I want to change its background color while the user is pressing it, and when the pressing is finished, it returns to its original color.

I tried to use a GestureDetector, implementing onTapDown and onTapUp functions, but it doesn't work: it takes a long time (~150ms) to change color and, if I tap at normal speed, the color doesn't change.

I am an Android developer, and what I want to do is done in Android using a selector as follows:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="..." android:state_pressed="true" />
  <item android:drawable="..." />
</selector>.

But I don't know how to do that with flutter. I hope the piece of code will help to understand what I want to achieve.

Body:
Here is how I would do it:

class MyWidget extends StatefulWidget {

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

class _MyWidgetState extends State<MyWidget> with SingleTickerProviderStateMixin {

  AnimationController _controller;
  Color myColor = Colors.blue;

  @override
  void initState() {
    _controller = AnimationController(vsync: this,duration: Duration(milliseconds: 400));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapUp: (_) {
        setState(() {
        myColor = Colors.blue;
        });
      },
      onTapDown: (_) {
        setState(() {
        myColor = Colors.red;
        });
      },
       child: AnimatedBuilder(animation: _controller,
       builder: (context, child) => Container(
         height: 200,
         width: 200,
         color : myColor,
       )),
    );
  }
}

You can change the duration in the animationController if it's too slow.


问:
Associations of Hierarchical Objects, belongs_to, has_many of Own Class
I'm trying to make objects belong to other objects of the same class by adding a parent_id attribute to the object so active record can associate them with each other in a hierarchical manner.

I know I can just write an instance method to do a find and get them, but I want to know if there is a more rails appropriate way to accomplish this, so can I set this up with active record associations, if so how?

答:
It seems that this gem may be of help :

https://github.com/skyeagle/nested_set

or acts_as_tree:

https://github.com/rails/acts_as_tree

ContentLicense: CC BY-SA 3.0


问:
How do I take the content of the Ace code editor with a laravel form
as the question says, I want to submit the code from the editor,but I don't know how can I do this using a laravel form. I found that I can use editor.getValue() here but don't know how to use it with laravel. I have the following code

```<code>
<style type="text/css" media="screen">
    #editor {
        position: absolute;
        top: 150px;
        right: 150px;
        bottom: 150px;
        left: 150px;
    }
    .ace_editor {
        border: 1px solid lightgray;
        margin: auto;
        height: 65%;
        width: 55%;
    }
    .scrollmargin {
        height: 80px;
        text-align: center;
    }
</style>

{!! Form::open(['action' => 'ProblemsController@store']) !!}
  <div id="editor">
    //Your code goes here
  </div>
  {{Form::submit('Submit')}}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.3.3/ace.js" type="text/javascript" charset="utf-8"></script>
  <script>
      var editor = ace.edit("editor");
      editor.setTheme("ace/theme/chrome");
      editor.session.setMode("ace/mode/c_cpp");
  </script>
{!! Form::close() !!}

</code>```

答:
You can add a hidden input and filled with editor.getValue() in onchange method. something like this:

Javascript

```<code>editor.session.on('change', function(delta) {
   var content=document.getElementById('hiddenInput');
   content.value=editor.getValue()
});
</code>```

HTML

```<code> <input name="hiddenInput" id="hiddenInput">
</code>```

Body:
as the question says, I want to submit the code from the editor,but I don't know how can I do this using a laravel form. I found that I can use editor.getValue() here but don't know how to use it with laravel. I have the following code

{!! Form::open(['action' => 'ProblemsController@store']) !!}

    //Your code goes here

  {{Form::submit('Submit')}}

{!! Form::close() !!}

Body:
You can add a hidden input and filled with editor.getValue() in onchange method. something like this:

Javascript

editor.session.on('change', function(delta) {
   var content=document.getElementById('hiddenInput');
   content.value=editor.getValue()
});

HTML

 <input name="hiddenInput" id="hiddenInput">


问:
How to access nested dictionary in python. how do i access total_cases
how do i access the total_cases, death in python   </p>

```<code>{'data': {'2020-05-28': {'critical': 0,
                         'death_ratio': 0.0047984644913627635,
                         'deaths': 5,
                         'recovered': 187,
                         'recovery_ratio': 0.17946257197696738,
                         'tested': 162730,
                         'total_cases': 1042},
          '2020-05-29': {'critical': 1000,
                         'death_ratio': 0.0049504950495049506,
                         'deaths': 6,
                         'recovered': 206,
                         'recovery_ratio': 0.16996699669966997,
                         'tested': 0,
                         'total_cases': 1212}},
 'status': 200,
 'type': 'stack'}
</code>```

答:
dictionary_name is the name of your variable.

```<code>dictionary_name["data"]["2020-05-29"]["total_cases"]

dictionary_name["data"]["2020-05-29"]["deaths"]
</code>```

Body:
how do i access the total_cases, death in python

{'data': {'2020-05-28': {'critical': 0,
                         'death_ratio': 0.0047984644913627635,
                         'deaths': 5,
                         'recovered': 187,
                         'recovery_ratio': 0.17946257197696738,
                         'tested': 162730,
                         'total_cases': 1042},
          '2020-05-29': {'critical': 1000,
                         'death_ratio': 0.0049504950495049506,
                         'deaths': 6,
                         'recovered': 206,
                         'recovery_ratio': 0.16996699669966997,
                         'tested': 0,
                         'total_cases': 1212}},
 'status': 200,
 'type': 'stack'}

Body:
dictionary_name is the name of your variable.

dictionary_name["data"]["2020-05-29"]["total_cases"]

dictionary_name["data"]["2020-05-29"]["deaths"]


问:
`window.onerror` hook not being called when throwing exception inside Promise
I've added an error hook using window.onerror, but when I throw inside of the cb to a .then of a Promise the hook doesn't fire. Is there a way to make the hook fire? I don't want to have to add a .catch

```<code>window.onerror = () => console.log('an error')

new Promise(_ => _())
  .then(() => {
    throw 'err'
  })

//the hook doesn't fire
</code>```

答:
An exception thrown inside a .then() handler is automatically caught by the promise and it turns the promise into a rejected promise so the exception does not bubble up to where it would be be seen by window.onerrror.

If you don't have a handler for the rejected promise, then you should get an unhandledrejection event as described here.

Body:
I've added an error hook using window.onerror, but when I throw inside of the cb to a .then of a Promise the hook doesn't fire. Is there a way to make the hook fire? I don't want to have to add a .catch

window.onerror = () => console.log('an error')

new Promise(_ => _())
  .then(() => {
    throw 'err'
  })

//the hook doesn't fire


问:
Getting error on deploying nestjs app on gcloud
Getting error on deploying nestjs app on google app engine. The deployment worked fine but app is giving error

Here is the my package.json file

"main": "dist/main.js",
  "engines": {
    "node": ">=8.0.0"
  },
  "scripts": {
    "prebuild": "rimraf dist",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "node ./dist/main.js",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "tslint -p tsconfig.json -c tslint.json",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "build": " tsc -p tsconfig.build.json",
    "gcp-build": "npm run build"
  },```
</div>
</div>
</p>

<p>and this my <strong>app.yaml</strong> file</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>runtime: nodejs10
env: standard</code>```

I tried to see the error on gcloud console by gcloud app logs read and it gives me error in cjs/loader file

The app is working fine locally. Any reason why this is happening?

答:
Error: Cannot find module 'src/utils'

It looks like you are using non-relative imports and using src as a root, which won't work once you have transpiled from typescript to javaScript without some extra modifications. The src directory shouldn't exist when you are in your production environment, only the dist that has your JavaScript. If you change the import to be a relative one (using .. to get tot the correct directory from where you are) it should work just fine

Body:
Getting error on deploying nestjs app on google app engine. The deployment worked fine but app is giving error

Here is the my package.json file

"main": "dist/main.js",
  "engines": {
    "node": ">=8.0.0"
  },
  "scripts": {
    "prebuild": "rimraf dist",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "node ./dist/main.js",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "tslint -p tsconfig.json -c tslint.json",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "build": " tsc -p tsconfig.build.json",
    "gcp-build": "npm run build"
  },

and this my app.yaml file

runtime: nodejs10
env: standard

I tried to see the error on gcloud console by gcloud app logs read and it gives me error in cjs/loader file

The app is working fine locally. Any reason why this is happening?


问:
Why a child div is not being removed when the height of parent div is decreased to 0?
I'm very new to HTML and CSS. So please bear with me.

I've a header div, which contains a nav div, which contains a li div. I was trying to implement a button which would hide the header. I'm able to hide the header, but I can still see the nav and li div.

The following are the css properties:

#header {
  z-index: 100;
  left:0;
  top: 0px;
  height: 60px;
  transition: max-height 0.2s ease-out;
  width: 100%;
  position: fixed;
    nav {
       max-width: 650px;
       margin: 0 auto;
       padding: 0 10px;
       li {
          font-family: 'OpenSansLight', "Helvetica Neue", Helvetica, Arial, sans-serif;
          font-weight: normal;
          list-style: none;
          display: inline;
          color: white;
          line-height: 50px;
       }
    }
}
```

<p>The above is a Jekyll <code>scss</code> file, which generates a corresponding <code>css</code>. The JavaScript function is as follows:</p>

<pre class="lang-js prettyprint-override"><code>var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    var content = this.nextElementSibling;
    console.log(content.innerHTML);
    if (content.style.height){
      content.style.height = null;
    } else {
      content.style.height = content.scrollHeight + "px";
    }
  });
}
</code>```

Thanks.

答:
Please use the display property as none. It will hide children divs also.
Use like this : display: 'none';

Body:
I'm very new to HTML and CSS. So please bear with me.

I've a header div, which contains a nav div, which contains a li div. I was trying to implement a button which would hide the header. I'm able to hide the header, but I can still see the nav and li div.

The following are the css properties:

#header {
  z-index: 100;
  left:0;
  top: 0px;
  height: 60px;
  transition: max-height 0.2s ease-out;
  width: 100%;
  position: fixed;
    nav {
       max-width: 650px;
       margin: 0 auto;
       padding: 0 10px;
       li {
          font-family: 'OpenSansLight', "Helvetica Neue", Helvetica, Arial, sans-serif;
          font-weight: normal;
          list-style: none;
          display: inline;
          color: white;
          line-height: 50px;
       }
    }
}

The above is a Jekyll scss file, which generates a corresponding css. The JavaScript function is as follows:

var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    var content = this.nextElementSibling;
    console.log(content.innerHTML);
    if (content.style.height){
      content.style.height = null;
    } else {
      content.style.height = content.scrollHeight + "px";
    }
  });
}

Thanks.


问:
Having problem with web scraping with bs4 in python
My program returns different numbers each time. If I run each page individually it gives out the right results. I wanted to get all the links which have 3 or more votes. </p>

```<code>from bs4 import BeautifulSoup as bs
import requests
import pandas
pg = 1
url ="https://stackoverflow.com/search?page="+str(pg)+"&tab=Relevance&q=scrappy%20python"
src = requests.get(url).text
soup = bs(src,'html.parser')
pages = soup.findAll('a',{'class' : 's-pagination--item js-pagination-item'})
number_of_pages = len(pages)
print(number_of_pages)
qualified=[]

while pg<=number_of_pages:
    print("In Page :"+str(pg))
    url = "https://stackoverflow.com/search?page=" + str(pg) + "&tab=Relevance&q=scrappy%20python"
    src = requests.get(url).text
    soup = bs(src, 'html.parser')
    a_links = soup.findAll('a',{'class':'question-hyperlink'})
    span_links = soup.findAll('span',{'class':'vote-count-post'})
    hrefs = []
    for a_link in a_links:
        hrefs.append(a_link.get('href'))
    for link in range(len(span_links)):
        vote = span_links[link].strong.text
        n = int(vote)
        if n>2:
            the_link = 'https://stackoverflow.com' + hrefs[link]
            qualified.append(the_link)
            print(len(qualified))

    pg +=1
</code>```

答:
print(len(qualified)) will show the length of the full list that is your error. You can get how many links in each by adding i = 0 after while pg<=number_of_pages: and i += 1 after if n>2: then add print(i) before or after pg +=1.
Then code will be like this:

```<code>from bs4 import BeautifulSoup as bs
import requests
import pandas
pg = 1
url ="https://stackoverflow.com/search?page="+str(pg)+"&tab=Relevance&q=scrappy%20python"
src = requests.get(url).text
soup = bs(src,'html.parser')
pages = soup.findAll('a',{'class' : 's-pagination--item js-pagination-item'})
number_of_pages = len(pages)
print(number_of_pages)
qualified=[]

while pg<=number_of_pages:
    i = 0
    print("In Page :"+str(pg))
    url = "https://stackoverflow.com/search?page=" + str(pg) + "&tab=Relevance&q=scrappy%20python"
    src = requests.get(url).text
    soup = bs(src, 'html.parser')
    a_links = soup.findAll('a',{'class':'question-hyperlink'})
    span_links = soup.findAll('span',{'class':'vote-count-post'})
    hrefs = []
    for a_link in a_links:
        hrefs.append(a_link.get('href'))
    for link in range(len(span_links)):
        vote = span_links[link].strong.text
        n = int(vote)
        if n>2:
            i += 1
            the_link = 'https://stackoverflow.com' + hrefs[link]
            qualified.append(the_link)
    print(i)

    pg +=1
#print(qualified)
</code>```

Output:

```<code>6
In Page :1
1
In Page :2
4
In Page :3
2
In Page :4
3
In Page :5
2
In Page :6
2
</code>```

Body:
My program returns different numbers each time. If I run each page individually it gives out the right results. I wanted to get all the links which have 3 or more votes.

from bs4 import BeautifulSoup as bs
import requests
import pandas
pg = 1
url ="https://stackoverflow.com/search?page="+str(pg)+"&tab=Relevance&q=scrappy%20python"
src = requests.get(url).text
soup = bs(src,'html.parser')
pages = soup.findAll('a',{'class' : 's-pagination--item js-pagination-item'})
number_of_pages = len(pages)
print(number_of_pages)
qualified=[]

while pg<=number_of_pages:
    print("In Page :"+str(pg))
    url = "https://stackoverflow.com/search?page=" + str(pg) + "&tab=Relevance&q=scrappy%20python"
    src = requests.get(url).text
    soup = bs(src, 'html.parser')
    a_links = soup.findAll('a',{'class':'question-hyperlink'})
    span_links = soup.findAll('span',{'class':'vote-count-post'})
    hrefs = []
    for a_link in a_links:
        hrefs.append(a_link.get('href'))
    for link in range(len(span_links)):
        vote = span_links[link].strong.text
        n = int(vote)
        if n>2:
            the_link = 'https://stackoverflow.com' + hrefs[link]
            qualified.append(the_link)
            print(len(qualified))

    pg +=1

Body:
print(len(qualified)) will show the length of the full list that is your error. You can get how many links in each by adding i = 0 after while pg<=number_of_pages: and i += 1 after if n>2: then add print(i) before or after pg +=1.
Then code will be like this:

from bs4 import BeautifulSoup as bs
import requests
import pandas
pg = 1
url ="https://stackoverflow.com/search?page="+str(pg)+"&tab=Relevance&q=scrappy%20python"
src = requests.get(url).text
soup = bs(src,'html.parser')
pages = soup.findAll('a',{'class' : 's-pagination--item js-pagination-item'})
number_of_pages = len(pages)
print(number_of_pages)
qualified=[]

while pg<=number_of_pages:
    i = 0
    print("In Page :"+str(pg))
    url = "https://stackoverflow.com/search?page=" + str(pg) + "&tab=Relevance&q=scrappy%20python"
    src = requests.get(url).text
    soup = bs(src, 'html.parser')
    a_links = soup.findAll('a',{'class':'question-hyperlink'})
    span_links = soup.findAll('span',{'class':'vote-count-post'})
    hrefs = []
    for a_link in a_links:
        hrefs.append(a_link.get('href'))
    for link in range(len(span_links)):
        vote = span_links[link].strong.text
        n = int(vote)
        if n>2:
            i += 1
            the_link = 'https://stackoverflow.com' + hrefs[link]
            qualified.append(the_link)
    print(i)

    pg +=1
#print(qualified)

Output:

6
In Page :1
1
In Page :2
4
In Page :3
2
In Page :4
3
In Page :5
2
In Page :6
2


问:
Check for cells containing strings with non-latin letter characters in Googlesheets using Regex with QUERY
I'm currently working with a database in Googlesheets containing app publishers linked to financial apps. I plan to match it with another list that has multiple bank names from multiple countries. The problem is that the first database has the names of the publishers as the original names, but second list has some bank names translated to English and some of them have the original native name. Specifically, the names of banks that appear to be written originally with a non-Latin script (such as Korean, Cyrillic, Japanese or Arabic) have been translated to English, and the names of banks that are written in a Latin-script-based language (as Spanish, Romanian, Slovenian or French) all appear to be not translated, just without any diacritic.

Because of this, i'm trying to use Regex in Googlesheets in order to check the cells for non-Latin Unicode letter characters (and that's why this question doesn't help, nor this one). Since currently Googlesheets' REGEXMATCH is incompatible with Unicode class characters, i've been forced to use the QUERY function (following this answer). Let's say that I have this column A:

```<code>A
融360
הבנק הבינלאומי
АТ "Акцент-Банк
АО АЛСЕКО
АО "Altyn Bank"
АКБ "Kapitalbank
Şekerbank
İninal
Československá obchodní banka
iBillionaire
iBear
iBankマーケティング株式会社
4finance
11번가(주)
11com7 design
1 2 3 Apps
1 2 3 Apps
(주)인포바인
</code>```

I want to use QUERY in another column combined with WHERE MATCHES in order to be able to use the Latin Unicode class, and I want the QUERY function to give results only when non-Latin letter characters appear. That is, I want something like this as a result in column B:

```<code>A:B
融360:融360
הבנק הבינלאומי:הבנק הבינלאומי
АТ "Акцент-Банк:АТ "Акцент-Банк
АО АЛСЕКО:АО АЛСЕКО
АО "Altyn Bank":АО "Altyn Bank" \\ These are Cyrillic A and O
АКБ "Kapitalbank:АКБ "Kapitalbank
Şekerbank:#N/A
İninal:#N/A
Československá obchodní banka:#N/A
iBillionaire:#N/A
iBear:#N/A
iBankマーケティング株式会社:iBankマーケティング株式会社
4finance:#N/A
11번가(주):11번가(주)
11com7 design:#N/A
1 2 3 Apps:#N/A
1 2 3 Apps:#N/A
(주)인포바인:(주)인포바인
</code>```

I'm doing this with this formula: =QUERY(A;"select A where A matches 'SomeREGEX'";0), but I don't seem to get the correct regular expression. After a lot of unsuccessful attempts, I tried [\p{Latin}\d\s]*[^\p{Latin}]+[\p{Latin}\d\s]* that gives a correct answer to АО АЛСЕКО, Československá obchodní banka, 11번가(주), 11com7 design and (주)인포바인, but not with АО "Altyn Bank", АКБ "Kapitalbank or iBankマーケティング株式会社

What I might be doing wrong?

答:
You may use

```<code>=REGEXMATCH(A1,".*([\x{0080}-\x{02AF}]|\d.*[a-zA-Z]|[a-zA-Z].*\d).*|^[a-zA-Z]+$")
</code>```

See the regex demo

Details

.* - any 0 or more chars other than line break chars, as many as possible

([\x{0080}-\x{02AF}]|\d.*[a-zA-Z]|[a-zA-Z].*\d) -

[\x{0080}-\x{02AF}] - a character from U+0080 to U+02AF range

| - or

\d.*[a-zA-Z]|[a-zA-Z].*\d - a digit, any 0+ chars as many as possible, ASCII letter, or an ASCII letter, then 0 or more chars as a digit after

.* - any 0 or more chars other than line break chars, as many as possible

| - or

^ - start of string

[a-zA-Z]+ - 1 or more ASCII letters

$ - end of string

Body:
I'm currently working with a database in Googlesheets containing app publishers linked to financial apps. I plan to match it with another list that has multiple bank names from multiple countries. The problem is that the first database has the names of the publishers as the original names, but second list has some bank names translated to English and some of them have the original native name. Specifically, the names of banks that appear to be written originally with a non-Latin script (such as Korean, Cyrillic, Japanese or Arabic) have been translated to English, and the names of banks that are written in a Latin-script-based language (as Spanish, Romanian, Slovenian or French) all appear to be not translated, just without any diacritic.

Because of this, i'm trying to use Regex in Googlesheets in order to check the cells for non-Latin Unicode letter characters (and that's why this question doesn't help, nor this one). Since currently Googlesheets' REGEXMATCH is incompatible with Unicode class characters, i've been forced to use the QUERY function (following this answer). Let's say that I have this column A:

A
融360
הבנק הבינלאומי
АТ "Акцент-Банк
АО АЛСЕКО
АО "Altyn Bank"
АКБ "Kapitalbank
Şekerbank
İninal
Československá obchodní banka
iBillionaire
iBear
iBankマーケティング株式会社
4finance
11번가(주)
11com7 design
1 2 3 Apps
1 2 3 Apps
(주)인포바인

I want to use QUERY in another column combined with WHERE MATCHES in order to be able to use the Latin Unicode class, and I want the QUERY function to give results only when non-Latin letter characters appear. That is, I want something like this as a result in column B:

A:B
融360:融360
הבנק הבינלאומי:הבנק הבינלאומי
АТ "Акцент-Банк:АТ "Акцент-Банк
АО АЛСЕКО:АО АЛСЕКО
АО "Altyn Bank":АО "Altyn Bank" \\ These are Cyrillic A and O
АКБ "Kapitalbank:АКБ "Kapitalbank
Şekerbank:#N/A
İninal:#N/A
Československá obchodní banka:#N/A
iBillionaire:#N/A
iBear:#N/A
iBankマーケティング株式会社:iBankマーケティング株式会社
4finance:#N/A
11번가(주):11번가(주)
11com7 design:#N/A
1 2 3 Apps:#N/A
1 2 3 Apps:#N/A
(주)인포바인:(주)인포바인

I'm doing this with this formula: =QUERY(A;"select A where A matches 'SomeREGEX'";0), but I don't seem to get the correct regular expression. After a lot of unsuccessful attempts, I tried [\p{Latin}\d\s]*[^\p{Latin}]+[\p{Latin}\d\s]* that gives a correct answer to АО АЛСЕКО, Československá obchodní banka, 11번가(주), 11com7 design and (주)인포바인, but not with АО "Altyn Bank", АКБ "Kapitalbank or iBankマーケティング株式会社

What I might be doing wrong?

Body:
You may use

=REGEXMATCH(A1,".*([\x{0080}-\x{02AF}]|\d.*[a-zA-Z]|[a-zA-Z].*\d).*|^[a-zA-Z]+$")

See the regex demo

Details

.* - any 0 or more chars other than line break chars, as many as possible

([\x{0080}-\x{02AF}]|\d.*[a-zA-Z]|[a-zA-Z].*\d) -

[\x{0080}-\x{02AF}] - a character from U+0080 to U+02AF range

| - or

\d.*[a-zA-Z]|[a-zA-Z].*\d - a digit, any 0+ chars as many as possible, ASCII letter, or an ASCII letter, then 0 or more chars as a digit after

.* - any 0 or more chars other than line break chars, as many as possible

| - or

^ - start of string

[a-zA-Z]+ - 1 or more ASCII letters

$ - end of string


问:
How to loop over an Array with JavaScript?
I have a string that has data separated by a pipe character (|).

Example

```<code>var somestring = "data1|data2|data3";
var separated = somestring.split("|");
</code>```

I know how to use the split() to separate each data.

However, I don't know how many pipes there will be in the resulting Array.

In jQuery or JavaScript, how do I loop over the array returned?

答: separated.length should be all you need.

Body:
I have a string that has data separated by a pipe character (|).

Example

var somestring = "data1|data2|data3";
var separated = somestring.split("|");

I know how to use the split() to separate each data.

However, I don't know how many pipes there will be in the resulting Array.

In jQuery or JavaScript, how do I loop over the array returned?


问:
SwiftUI TextField touchable Area
SwiftUI layout is very different from what we are used to. Currently I'm fighting against TextFields. Specifically their touchable Area.

```<code>TextField(
    .constant(""),
    placeholder: Text("My text field")
    )
        .padding([.leading, .trailing])
        .font(.body)
</code>```

This results in a very small TextField (height wise)

Adding the frame modifier fixes the issue (visually)

```<code>TextField(
    .constant(""),
    placeholder: Text("My text field")
    ).frame(height: 60)
        .padding([.leading, .trailing])
        .font(.body)
</code>```

but the touchable area remains the same.

I'm aware of the fact that the frame modifier does nothing else other than wrap the textField in another View with the specified height.

Is there any equivalent to resizable() for Image that will allow a taller TextField with wider touchable Area?

答:
Solution with Button

If you don't mind using Introspect you can do it by saving the UITextField and calling becomeFirstResponder() on button press.

extension View {
    public func textFieldFocusableArea() -> some View {
        TextFieldButton { self.contentShape(Rectangle()) }
    }
}

fileprivate struct TextFieldButton: View {
    init(label: @escaping () -> Label) {
        self.label = label
    }

    var label: () -> Label

    private var textField = Weak<UITextField>(nil)

    var body: some View {
        Button(action: {
            self.textField.value?.becomeFirstResponder()
        }, label: {
            label().introspectTextField {
                self.textField.value = $0
            }
        }).buttonStyle(PlainButtonStyle())
    }
}

/// Holds a weak reference to a value
public class Weak<T: AnyObject> {
    public weak var value: T?
    public init(_ value: T?) {
        self.value = value
    }
}
```
<p>Example usage:</p>
<pre class="lang-swift prettyprint-override"><code>TextField(...)
    .padding(100)
    .textFieldFocusableArea()
</code>```

Since I use this myself as well, I will keep it updated on github: https://gist.github.com/Amzd/d7d0c7de8eae8a771cb0ae3b99eab73d

New solution using ResponderChain

The Button solution will add styling and animation which might not be wanted therefore I now use a new method using my ResponderChain package

import ResponderChain

extension View {
    public func textFieldFocusableArea() -> some View {
        self.modifier(TextFieldFocusableAreaModifier())
    }
}

fileprivate struct TextFieldFocusableAreaModifier: ViewModifier {
    @EnvironmentObject private var chain: ResponderChain
    @State private var id = UUID()

    func body(content: Content) -> some View {
        content
            .contentShape(Rectangle())
            .responderTag(id)
            .onTapGesture {
                chain.firstResponder = id
            }
    }
}
```

You'll have to set the ResponderChain as environment object in the SceneDelegate, check the README of ResponderChain for more info.

Title: SwiftUI TextField touchable Area

Body:
SwiftUI layout is very different from what we are used to. Currently I'm fighting against TextFields. Specifically their touchable Area.

TextField(
    .constant(""),
    placeholder: Text("My text field")
    )
        .padding([.leading, .trailing])
        .font(.body)

This results in a very small TextField (height wise)

Adding the frame modifier fixes the issue (visually)

TextField(
    .constant(""),
    placeholder: Text("My text field")
    ).frame(height: 60)
        .padding([.leading, .trailing])
        .font(.body)

but the touchable area remains the same.

I'm aware of the fact that the frame modifier does nothing else other than wrap the textField in another View with the specified height.

Is there any equivalent to resizable() for Image that will allow a taller TextField with wider touchable Area?

Body:
Solution with Button

If you don't mind using Introspect you can do it by saving the UITextField and calling becomeFirstResponder() on button press.

extension View {
    public func textFieldFocusableArea() -> some View {
        TextFieldButton { self.contentShape(Rectangle()) }
    }
}

fileprivate struct TextFieldButton<Label: View>: View {
    init(label: @escaping () -> Label) {
        self.label = label
    }

    var label: () -> Label

    private var textField = Weak<UITextField>(nil)

    var body: some View {
        Button(action: {
            self.textField.value?.becomeFirstResponder()
        }, label: {
            label().introspectTextField {
                self.textField.value = $0
            }
        }).buttonStyle(PlainButtonStyle())
    }
}

/// Holds a weak reference to a value
public class Weak<T: AnyObject> {
    public weak var value: T?
    public init(_ value: T?) {
        self.value = value
    }
}

Example usage:

TextField(...)
    .padding(100)
    .textFieldFocusableArea()

Since I use this myself as well, I will keep it updated on github: https://gist.github.com/Amzd/d7d0c7de8eae8a771cb0ae3b99eab73d

New solution using ResponderChain

The Button solution will add styling and animation which might not be wanted therefore I now use a new method using my ResponderChain package

import ResponderChain

extension View {
    public func textFieldFocusableArea() -> some View {
        self.modifier(TextFieldFocusableAreaModifier())
    }
}

fileprivate struct TextFieldFocusableAreaModifier: ViewModifier {
    @EnvironmentObject private var chain: ResponderChain
    @State private var id = UUID()

    func body(content: Content) -> some View {
        content
            .contentShape(Rectangle())
            .responderTag(id)
            .onTapGesture {
                chain.firstResponder = id
            }
    }
}

You'll have to set the ResponderChain as environment object in the SceneDelegate, check the README of ResponderChain for more info.


问:
how do I set my Iframe in screen for mobile devices
```<code>My css for Iframe:

position: absolute;
right: 0;
top: -100px;
z-index: 1;
height: 110%;
width: 100%;
border: none;
overflow-y: auto;
overflow-x: hidden;
</code>```

This is my CSS for Iframe screen on my website, but in mobile devices, I have to scroll the Iframe screen to see the full website.
Note: making the iframe responsive is not in my hand.

答:
The bootstrap method. Use an iframe or video element in it.

```<code><div class="embed-16by9">
  <iframe src="..."></iframe>
</div>
</code>```

with responsive css

```<code>embed-16by9 {
  position: relative;
  display: block;
  width: 100%;
  padding: 0;
  overflow: hidden;
}
.embed-16by9::before {
  display: block;
  content: "";
  padding-top: 56.25%; /* ratio 16:9 */
}
.embed-16by9 iframe,
.embed-16by9 video {
  width: 100%;
  border: 0;
  position: absolute;
  top: 0; bottom: 0; left: 0;
  height: 100%;
}
</code>```

Body:
My css for Iframe:

position: absolute;
right: 0;
top: -100px;
z-index: 1;
height: 110%;
width: 100%;
border: none;
overflow-y: auto;
overflow-x: hidden;

This is my CSS for Iframe screen on my website, but in mobile devices, I have to scroll the Iframe screen to see the full website.
Note: making the iframe responsive is not in my hand.

Body:
The bootstrap method. Use an iframe or video element in it.

<div class="embed-16by9">
  <iframe src="..."></iframe>
</div>

with responsive css

embed-16by9 {
  position: relative;
  display: block;
  width: 100%;
  padding: 0;
  overflow: hidden;
}
.embed-16by9::before {
  display: block;
  content: "";
  padding-top: 56.25%; /* ratio 16:9 */
}
.embed-16by9 iframe,
.embed-16by9 video {
  width: 100%;
  border: 0;
  position: absolute;
  top: 0; bottom: 0; left: 0;
  height: 100%;
}


问:
ReferenceError: Cannot access 'embed' before initialization
Here is my code, but I don't know to where should I put that "const embed = new Discord.RichEmbed()" line.

```<code>    const Discord = require("discord.js");

module.exports = {
  name: "events",
  description: "Display the events!",
  execute(message, bot, args){
    message.channel.sendEmbed(embed);
  const embed = new Discord.RichEmbed()
  .setTitle("Event Times")
  .setDescription("Server's timezone: UTC+3")
  .setThumbnail("https://i.imgur.com/Jk5Wxj3.png")
  .addFields(
      { name: '\u200B', value: '\u200B' },
      { name: 'Monday', value: 'DemaNeR - Start 8AM' }, // Value is the event name and time.
      { name: 'Tuesday', value: 'Spaceball - Start 6PM' }, // value: 'new value'
      { name: 'Wednesday', value: 'JPB- Start 10PM' },
      { name: 'Thursday', value: 'Invasion - Start 9PM' },
      { name: 'Friday', value: 'Hitac - Start 4PM' },
      { name: 'Saturday', value: 'CVC(Infiltration) - All Day' },
      { name: 'Sunday', value: 'JPB - Start 7PM ->> Invasion - Start 10PM' },
  )
  .setColor("#f36639")

}

  }
</code>```

答:
just switch these two lines </p>

```<code>   message.channel.sendEmbed(embed);
  const embed = new Discord.RichEmbed()
</code>```

<p>to be </p>

```<code>   const embed = new Discord.RichEmbed();
   message.channel.sendEmbed(embed);
</code>```

Body:
Here is my code, but I don't know to where should I put that "const embed = new Discord.RichEmbed()" line.

    const Discord = require("discord.js");

module.exports = {
  name: "events",
  description: "Display the events!",
  execute(message, bot, args){
    message.channel.sendEmbed(embed);
  const embed = new Discord.RichEmbed()
  .setTitle("Event Times")
  .setDescription("Server's timezone: UTC+3")
  .setThumbnail("https://i.imgur.com/Jk5Wxj3.png")
  .addFields(
      { name: '\u200B', value: '\u200B' },
      { name: 'Monday', value: 'DemaNeR - Start 8AM' }, // Value is the event name and time.
      { name: 'Tuesday', value: 'Spaceball - Start 6PM' }, // value: 'new value'
      { name: 'Wednesday', value: 'JPB- Start 10PM' },
      { name: 'Thursday', value: 'Invasion - Start 9PM' },
      { name: 'Friday', value: 'Hitac - Start 4PM' },
      { name: 'Saturday', value: 'CVC(Infiltration) - All Day' },
      { name: 'Sunday', value: 'JPB - Start 7PM ->> Invasion - Start 10PM' },
  )
  .setColor("#f36639")

}

  }

Body:
just switch these two lines

   message.channel.sendEmbed(embed);
  const embed = new Discord.RichEmbed()

to be

   const embed = new Discord.RichEmbed();
   message.channel.sendEmbed(embed);


问:
How to use secure flag when AuthenticationTypes.Sealing is used
I am creating a Directory Entry object using

```<code>System.DirectoryServices.DirectoryEntry dirEntry = new System.DirectoryServices.DirectoryEntry(path,
                    null, null, System.DirectoryServices.AuthenticationTypes.Sealing))
</code>```

It gives me warning: The Secure flag must also be set to use sealing.
What do I need to do ? I can suppress the above warning by using

```<code>#pragma warning disable S4433 // LDAP connections should be authenticated
</code>```

Can you please explain me what am i missing?
Please note, I am using AuthenticationTypes.Sealing because I want to create and set the user password in AD in a single commit from performance perspective.

Kindly explain.

答:
The AuthenticationTypes enum is  bit flag, meaning that multiple values can be combined. The error is saying that you cannot use Sealing without Secure. So you must include both, which you can do with |, like this:

```<code>DirectoryEntry dirEntry = new DirectoryEntry(path,
    null, null, AuthenticationTypes.Sealing | AuthenticationTypes.Secure);
</code>```

Body:
I am creating a Directory Entry object using

System.DirectoryServices.DirectoryEntry dirEntry = new System.DirectoryServices.DirectoryEntry(path,
                    null, null, System.DirectoryServices.AuthenticationTypes.Sealing))

It gives me warning: The Secure flag must also be set to use sealing.
What do I need to do ? I can suppress the above warning by using

#pragma warning disable S4433 // LDAP connections should be authenticated

Can you please explain me what am i missing?
Please note, I am using AuthenticationTypes.Sealing because I want to create and set the user password in AD in a single commit from performance perspective.

Kindly explain.

Body:
The AuthenticationTypes enum is  bit flag, meaning that multiple values can be combined. The error is saying that you cannot use Sealing without Secure. So you must include both, which you can do with |, like this:

DirectoryEntry dirEntry = new DirectoryEntry(path,
    null, null, AuthenticationTypes.Sealing | AuthenticationTypes.Secure);


问:
What are "BIN" files on github?
I wanted to upload some .java files on github, I don't remember if I uploaded the right files. I have been told that the files I should've submitted were missing. I checked the last commit, and the files I should've submitted were marked with "BIN" and were of type "classname".class instead of "classname".java, underneath each one of them it says "Binary file not shown" instead of the code. I would like to know what happened so that I can avoid this in the future. I have never experienced this before on github. What did I upload? I don't think I had any .class files regarding this project. </p>

答:
/bin is usually a folder that contains binary files or compiled stuff in general. You should never put it in a repo.

It's not dangerous, but it wastes space and it's something that has to be compiled in each one's computer anyway, so it's pointless to put them in the repo :)

Title: What are "BIN" files on github?


问:
CosmosDB SQL: how to use ARRAY_CONCAT or ARRAY(select distinct ...) as aggregate function?
I have a collection in Azure CosmosDB where each document has 2 fields, say

```<code>{"a":1,"b":2}
{"a":1,"b":3}
{"a":2,"b":5}
</code>```

and I want to return a set of possible values of B for each A, like this:

```<code>[{"a":1, "b":[2,3] },
 {"a":2, "b":[5]   }]
</code>```

Trying SELECT c.a, ARRAY(SELECT DISTINCT c.b FROM c) FROM c GROUP BY c.a
I receive the error

Property reference 'c.b' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Same for ARRAY(select value c.b from c); and ARRAY_CONCAT does not look like an aggregate function.

Are there ways to do it without aggregating client-side?

答:
Per my knowledge, this is not supported in Cosmos Db so far. Because Array is not aggregate function anyway which means it can't used with group by.

So, i suppose that you need to retrieve the data sort by a. Then loop the result to produce the b array mapping to the duplicate a.

Body:
I have a collection in Azure CosmosDB where each document has 2 fields, say

{"a":1,"b":2}
{"a":1,"b":3}
{"a":2,"b":5}

and I want to return a set of possible values of B for each A, like this:

[{"a":1, "b":[2,3] },
 {"a":2, "b":[5]   }]

Trying SELECT c.a, ARRAY(SELECT DISTINCT c.b FROM c) FROM c GROUP BY c.a
I receive the error

Property reference 'c.b' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Same for ARRAY(select value c.b from c); and ARRAY_CONCAT does not look like an aggregate function.

Are there ways to do it without aggregating client-side?


问:
TensorRT increasing memory usage (leak?)
I'm having a loop where I parse an ONNX model into TensorRT, create an engine and do inference.
I make sure I call x->destroy() on all objects and I use cudaFree for each cudaMalloc.
Yet, I keep getting an increase in memory usage through nvidia-smi over consecutive iterations.
I'm really not sure where the problem comes from. The cuda-memcheck tool reports no leaks either.
Running Ubuntu 18.04, TensorRT 7.0.0, CUDA 10.2 and using a GTX 1070.
The code, the ONNX file along with a CMakeLists.txt are available on this repo

Here's the code

#include <memory>
#include <iostream>
#include <cuda_runtime_api.h>
#include <NvOnnxParser.h>
#include <NvInfer.h>

class Logger : public nvinfer1::ILogger
{
    void log(Severity severity, const char* msg) override
    {
        // suppress info-level messages
        if (severity != Severity::kINFO)
            std::cout << msg << std::endl;
    }
};

int main(int argc, char * argv[])
{
    Logger gLogger;

    auto builder = nvinfer1::createInferBuilder(gLogger);

    const auto explicitBatch = 1U << static_cast<uint32_t>(nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
    auto network = builder->createNetworkV2(explicitBatch);

    auto config = builder->createBuilderConfig();

    auto parser = nvonnxparser::createParser(*network, gLogger);

    parser->parseFromFile("../model.onnx", static_cast<int>(0));
    builder->setMaxBatchSize(1);
    config->setMaxWorkspaceSize(128 * (1 << 20)); // 128 MiB

    auto engine = builder->buildEngineWithConfig(*network, *config);

    builder->destroy();
    network->destroy();
    parser->destroy();
    config->destroy();

    for(int i=0; i< atoi(argv[1]); i++)
    {
        auto context = engine->createExecutionContext();
        void* deviceBuffers[2]{0};

        int inputIndex = engine->getBindingIndex("input_rgb:0");
        constexpr int inputNumel = 1 * 128 * 64 * 3;
        int outputIndex = engine->getBindingIndex("truediv:0");
        constexpr int outputNumel = 1 * 128;

        //TODO: Remove batch size hardcoding
        cudaMalloc(&deviceBuffers[inputIndex], 1 * sizeof(float) * inputNumel);
        cudaMalloc(&deviceBuffers[outputIndex], 1 * sizeof(float) * outputNumel);

        cudaStream_t stream;
        cudaStreamCreate(&stream);

        float inBuffer[inputNumel] = {0};
        float outBuffer[outputNumel] = {0};

        cudaMemcpyAsync(deviceBuffers[inputIndex], inBuffer, 1 * sizeof(float) * inputNumel, cudaMemcpyHostToDevice, stream);

        context->enqueueV2(deviceBuffers, stream, nullptr);

        cudaMemcpyAsync(outBuffer, deviceBuffers[outputIndex], 1 * sizeof(float) * outputNumel, cudaMemcpyDeviceToHost, stream);

        cudaStreamSynchronize(stream);

        cudaFree(deviceBuffers[inputIndex]);
        cudaFree(deviceBuffers[outputIndex]);

        cudaStreamDestroy(stream);

        context->destroy();
    }
    engine->destroy();

    return 0;
}

```

答: Looks like the issue was coming from the repetitive IExecutionContext creation despite destroying it at the end of every iteration. Creating/deleting the context at the same time as the engine fixed the issue for me. Nevertheless, it could still be a bug where context creation leaks a little bit of memory and that leak accumulates over time. Filed a github issue.</p>


问:
finding the unpaired integer with O(logN)
I stumbled upon this quiz:

A non-empty array A consisting of N integers is given.

  The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

  E.G

    A = [9,3,9,3,5,7,5 ] // 3, 5 and 9 can be paired while 7 is left alone

  Write a efficient function that given an array A of N integers returns the value of the unpaired element.

  Note:

  1) N is an odd integer within the range [1..1,000,000];

  2) each element of array A is an integer within the range [1..1,000,000,000];

  3) all but one of the values in A occur an even number of times.

here's my solution, which is not considered efficient because it's complexity is O(N**2).

```<code>function solution(A) {
    let res;
    A.sort();
    //3,3,7,9,9,9,9
    while(A.length>1) {
        if(A[0] === A[1]) {
            A.shift();
            A.shift();
        } else {
            res = A[0];
            break;
        }
    }
    res = A.length === 1 ? A[0] : res;
    return res;
}
</code>```

How do i improve this from here?

Here the failing tests:

答:
thanks @Bindy1

here's the code i wrote based on your suggestion.

```<code>function solution(A) {
    let mySet = new Set();
    let auxFn;
    A.forEach( item => {
        auxFn = mySet.has(item) ? 'delete' : 'add';
        mySet[auxFn](item);
    });
    return [...mySet][0];
}
</code>```

Body:
I stumbled upon this quiz:

A non-empty array A consisting of N integers is given.

  The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

  E.G

    A = [9,3,9,3,5,7,5 ] // 3, 5 and 9 can be paired while 7 is left alone

  Write a efficient function that given an array A of N integers returns the value of the unpaired element.

  Note:

  1) N is an odd integer within the range [1..1,000,000];

  2) each element of array A is an integer within the range [1..1,000,000,000];

  3) all but one of the values in A occur an even number of times.

here's my solution, which is not considered efficient because it's complexity is O(N**2).

function solution(A) {
    let res;
    A.sort();
    //3,3,7,9,9,9,9
    while(A.length>1) {
        if(A[0] === A[1]) {
            A.shift();
            A.shift();
        } else {
            res = A[0];
            break;
        }
    }
    res = A.length === 1 ? A[0] : res;
    return res;
}

How do i improve this from here?

Here the failing tests:

Body:
thanks @Bindy1

here's the code i wrote based on your suggestion.

function solution(A) {
    let mySet = new Set();
    let auxFn;
    A.forEach( item => {
        auxFn = mySet.has(item) ? 'delete' : 'add';
        mySet[auxFn](item);
    });
    return [...mySet][0];
}


问:
Partially viewable bottom sheet - flutter
Is it possible in flutter to have the bottom sheet partially viewable at an initial state and then be able to either expand/dismiss?

I've included a screenshot of an example that Google Maps implements.

答:
Use the DraggableScrollableSheet widget with the Stack widget:

Here's the gist for the entire page in this^ GIF, or try the Codepen.

Here's the structure of the entire page:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          CustomGoogleMap(),
          CustomHeader(),
          DraggableScrollableSheet(
            initialChildSize: 0.30,
            minChildSize: 0.15,
            builder: (BuildContext context, ScrollController scrollController) {
              return SingleChildScrollView(
                controller: scrollController,
                child: CustomScrollViewContent(),
              );
            },
          ),
        ],
      ),
    );
  }
```
<p><br>In the <code>Stack</code>:
<br> - The Google map is the lower most layer.
<br> - The Header (search field + horizontally scrolling chips) is above the map.
<br> - The DraggableBottomSheet is above the Header.</p>
<p>Some useful parameters as defined in <code>draggable_scrollable_sheet.dart</code>:</p>
<pre class="lang-dart prettyprint-override"><code>  /// The initial fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `0.5`.
  final double initialChildSize;

  /// The minimum fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `0.25`.
  final double minChildSize;

  /// The maximum fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `1.0`.
  final double maxChildSize;
</code>```

Edit: Thank you @Alejandro for pointing out the typo in the widget name :)

Body:
Use the DraggableScrollableSheet widget with the Stack widget:

Here's the gist for the entire page in this^ GIF, or try the Codepen.

Here's the structure of the entire page:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          CustomGoogleMap(),
          CustomHeader(),
          DraggableScrollableSheet(
            initialChildSize: 0.30,
            minChildSize: 0.15,
            builder: (BuildContext context, ScrollController scrollController) {
              return SingleChildScrollView(
                controller: scrollController,
                child: CustomScrollViewContent(),
              );
            },
          ),
        ],
      ),
    );
  }

In the Stack:

 - The Google map is the lower most layer.

 - The Header (search field + horizontally scrolling chips) is above the map.

 - The DraggableBottomSheet is above the Header.

Some useful parameters as defined in draggable_scrollable_sheet.dart:

  /// The initial fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `0.5`.
  final double initialChildSize;

  /// The minimum fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `0.25`.
  final double minChildSize;

  /// The maximum fractional value of the parent container's height to use when
  /// displaying the widget.
  ///
  /// The default value is `1.0`.
  final double maxChildSize;

Edit: Thank you @Alejandro for pointing out the typo in the widget name :)


问:
How do I get IntelliJ IDEA to align all fields of a class?
My question is somewhat similar to this one:
How do I get IntelliJ IDEA to align adjacent variable assignments on the "=" sign?

The only difference is that option aligns only when they are grouped. But I want all fields to be aligned, regardless the groups:

```<code>public class Clazz {

   Integer qaz;
   Integer wsx;

   final Integer qwe = 111;
   final Integer asd = 222;
   final Integer zxc = 333;

   final Integer tyutyu = 444;
   final Integer ghjghj = 555;
...
}
</code>```

into

```<code>public class Clazz {

   Integer       qaz;
   Integer       wsx;

   final Integer qwe    = 111;
   final Integer asd    = 222;
   final Integer zxc    = 333;

   final Integer tyutyu = 444;
   final Integer ghjghj = 555;
...
}
</code>```

答:
Not possible at the moment, but a feature request exists for this case: IDEA-149359.

Feel free to vote for it.

Body:
My question is somewhat similar to this one:
How do I get IntelliJ IDEA to align adjacent variable assignments on the "=" sign?

The only difference is that option aligns only when they are grouped. But I want all fields to be aligned, regardless the groups:

public class Clazz {

   Integer qaz;
   Integer wsx;

   final Integer qwe = 111;
   final Integer asd = 222;
   final Integer zxc = 333;

   final Integer tyutyu = 444;
   final Integer ghjghj = 555;
...
}

into

public class Clazz {

   Integer       qaz;
   Integer       wsx;

   final Integer qwe    = 111;
   final Integer asd    = 222;
   final Integer zxc    = 333;

   final Integer tyutyu = 444;
   final Integer ghjghj = 555;
...
}


答:
In jQuery or JavaScript, how do I loop through each separated variable?

You basically just need to iterate over the resulting Array.

jQuery

$.each loop

This method is easy to work with, and benefits in the variables used being encapsulated.

```<code>$.each(separated, function(index, chunk) {
    // `chunk` is each member of the array.
});
</code>```

jsFiddle.

Of course, jQuery is JavaScript so any of the below methods will also work.

JavaScript

for loop

This is the recommended way.

```<code>for (var i = 0, length = separated.length; i < length; i++) {
    var chunk = separated[i];
    // `chunk` is each member of the array.
}
</code>```

jsFiddle.

You'll notice too the length property is cached so it is not looked up on each iteration. Some browsers already optimise for this, however IE appears to still benefit from it cached. It only takes 5 seconds to do, so you may as well keep IE users happy too.

You may want to define i and chunk outside of the for loop, because JavaScript has no block scope (unless you're using let), and those variables will exist before (declaration hoisted) and after (no block scope).

for ( in ) loop

This loop is generally not recommended, as it should be used for iterating over object properties only, not array like member properties.

```<code>for (var chunk in separated) {
     if ( ! separated.hasOwnProperty(chunk)) {
         continue;
     }
     // `separated[chunk]` is each member of the array.
}
</code>```

jsFiddle.

This loop will loop over all properties up the prototype chain, so hasOwnProperty() must be used. For this reason it is not recommended for arrays.

for ( of ) loop

This loop is standardized in ECMA 6 and is able to loop over NodeLists and iterators.

```<code>for (var chunk of separated) {
     // `chunk` is each member of the array.
}
</code>```

jsFiddle

forEach() method

This method is an addition to the ECMA-262 standard. It's not available in IE8, but it can be shimmed relatively easily.

```<code>separated.forEach(function(chunk, index) {
     // `chunk` is each member of the array.
});
</code>```

jsFiddle.

Other specialised methods

If you're looking to iterate for a specific goal, it may be useful to use a specialised iterator. Keep in mind these also don't have the best browser support.

filter method

Creates a mew array of the elements which the associated callback returned truthy for.

```<code>separated.filter(function(element) {
    return +element > 255;
});
</code>```

reduce method

Creates a new value based on reducing the elements of the array, from left to right.

```<code>separated.reduce(function(accumulator, element) {
    return accumulator.concat(element);
}, "");
</code>```

See also the reduceRight method.

map method

Creates a new array, replacing each element with the returned value of the associated callback.

```<code>separated.map(function(element) {
    return element.substr(0, 1);
});
</code>```

every method

Returns a boolean value of which is the result of every element in the array passing the test. This method short circuits, i.e. it returns whenever one element's callback doesn't return truthy.

```<code>separated.every(function(element) {
    return element.substr(0, 1) == "a";
});
</code>```

some method

Returns a boolean value of which is the result of some element in the array passing the test. This method short circuits, i.e. it returns whenever one element's callback passes the test.

```<code>separated.some(function(element) {
    return element.substr(0, 1) == "a";
});
</code>```

Title: How to loop over an Array with JavaScript?

Body:
In jQuery or JavaScript, how do I loop through each separated variable?

You basically just need to iterate over the resulting Array.

jQuery

$.each loop

This method is easy to work with, and benefits in the variables used being encapsulated.

$.each(separated, function(index, chunk) {
    // `chunk` is each member of the array.
});

jsFiddle.

Of course, jQuery is JavaScript so any of the below methods will also work.

JavaScript

for loop

This is the recommended way.

for (var i = 0, length = separated.length; i < length; i++) {
    var chunk = separated[i];
    // `chunk` is each member of the array.
}

jsFiddle.

You'll notice too the length property is cached so it is not looked up on each iteration. Some browsers already optimise for this, however IE appears to still benefit from it cached. It only takes 5 seconds to do, so you may as well keep IE users happy too.

You may want to define i and chunk outside of the for loop, because JavaScript has no block scope (unless you're using let), and those variables will exist before (declaration hoisted) and after (no block scope).

for ( in ) loop

This loop is generally not recommended, as it should be used for iterating over object properties only, not array like member properties.

for (var chunk in separated) {
     if ( ! separated.hasOwnProperty(chunk)) {
         continue;
     }
     // `separated[chunk]` is each member of the array.
}

jsFiddle.

This loop will loop over all properties up the prototype chain, so hasOwnProperty() must be used. For this reason it is not recommended for arrays.

for ( of ) loop

This loop is standardized in ECMA 6 and is able to loop over NodeLists and iterators.

for (var chunk of separated) {
     // `chunk` is each member of the array.
}

jsFiddle

forEach() method

This method is an addition to the ECMA-262 standard. It's not available in IE8, but it can be shimmed relatively easily.

separated.forEach(function(chunk, index) {
     // `chunk` is each member of the array.
});

jsFiddle.

Other specialised methods

If you're looking to iterate for a specific goal, it may be useful to use a specialised iterator. Keep in mind these also don't have the best browser support.

filter method

Creates a mew array of the elements which the associated callback returned truthy for.

separated.filter(function(element) {
    return +element > 255;
});

reduce method

Creates a new value based on reducing the elements of the array, from left to right.

separated.reduce(function(accumulator, element) {
    return accumulator.concat(element);
}, "");

See also the reduceRight method.

map method

Creates a new array, replacing each element with the returned value of the associated callback.

separated.map(function(element) {
    return element.substr(0, 1);
});

every method

Returns a boolean value of which is the result of every element in the array passing the test. This method short circuits, i.e. it returns whenever one element's callback doesn't return truthy.

separated.every(function(element) {
    return element.substr(0, 1) == "a";
});

some method

Returns a boolean value of which is the result of some element in the array passing the test. This method short circuits, i.e. it returns whenever one element's callback passes the test.

separated.some(function(element) {
    return element.substr(0, 1) == "a";
});


问:
Ember Routing - Dynamic Segment - Passing model through <LinkTo>
I am using Ember 3.18 and i have issue with dynamic segment. Here is my router.js

```<code>Router.map(function() {

    this.route('posts');

    this.route('post' , {path:"/post/:post_id"});

});
</code>```

When I try to perform a transition from posts route (which contains all the posts) to post/:post_id (which displays the details of the particular post) using the following

```<code><div>
{{#each this.data as |data|}}

   <LinkTo @route="dashboard.inbox-mail" @model={{data.id}}>

    <div class="card">
      <div>
        <p class="name">{{data.name}}</p>
      </div>
      <div>
        <p class="title">{{data.title}}</p>
        <p class="date">{{data.timestamp}}</p>
      </div>
    </div>

  </LinkTo>

 {{/each}}
</div>
</code>```

it does not performs the transition to the post/:post_id. The data contains following attributes

id - string
name - string
title - string
message - string
timestamp - string

my goal is to pass the post id to post/:post_id and make a API call in the model hook of post/:post_id.

I was able to perform transition using the below code but the downside is that the beforemodel and model hook are not called. Passing the entire data as model results in not calling the model and beforemodel

```<code><div>
{{#each this.data as |data|}}
   <LinkTo @route="dashboard.inbox-mail" @model={{data}}>
    <div class="card">
      <div>
        <p class="name">{{data.name}}</p>
      </div>
      <div>
        <p class="title">{{data.title}}</p>
        <p class="date">{{data.timestamp}}</p>
      </div>
    </div>
  </LinkTo>
  {{/each}}
</div>
</code>```

答:
change this.data to

```<code>{{#each @model as |data|}}
</code>```

Here is a good example similar to yours:
https://emberigniter.com/getting-started-ember-octane-tutorial/

Body:
I am using Ember 3.18 and i have issue with dynamic segment. Here is my router.js

Router.map(function() {

    this.route('posts');

    this.route('post' , {path:"/post/:post_id"});

});

When I try to perform a transition from posts route (which contains all the posts) to post/:post_id (which displays the details of the particular post) using the following

{{#each this.data as |data|}}

   <LinkTo @route="dashboard.inbox-mail" @model={{data.id}}>

{{data.name}}

{{data.title}}

{{data.timestamp}}

  </LinkTo>

 {{/each}}

it does not performs the transition to the post/:post_id. The data contains following attributes

id - string
name - string
title - string
message - string
timestamp - string

my goal is to pass the post id to post/:post_id and make a API call in the model hook of post/:post_id.

I was able to perform transition using the below code but the downside is that the beforemodel and model hook are not called. Passing the entire data as model results in not calling the model and beforemodel

{{#each this.data as |data|}}
   <LinkTo @route="dashboard.inbox-mail" @model={{data}}>

{{data.name}}

{{data.title}}

{{data.timestamp}}

  </LinkTo>
  {{/each}}

Body:
change this.data to

{{#each @model as |data|}}

Here is a good example similar to yours:
https://emberigniter.com/getting-started-ember-octane-tutorial/


问:
how to solve flutter android arm 64 error
I'm trying to run my flutter app on a real device but it gives me this error

Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.

Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

```<code> Required by:

     project :app

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'https://dl.google.com/dl/android/maven2/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'https://dl.google.com/dl/android/maven2/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > dl.google.com

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'https://jcenter.bintray.com/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'https://jcenter.bintray.com/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > jcenter.bintray.com

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > download.flutter.io

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > download.flutter.io

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > download.flutter.io
</code>```

if anybody knows how to fix it please help.

答:
```<code>> Could not GET 'http://
</code>```

suggests that your internet is not working as expected. Maybe you are using a vpn? In that case, suspend it for a few minutes. If not, it is another internet related issue...

Body:
I'm trying to run my flutter app on a real device but it gives me this error

Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

Could not resolve all task dependencies for configuration ':app:debugCompileClasspath'.

Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

 Required by:

     project :app

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'https://dl.google.com/dl/android/maven2/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'https://dl.google.com/dl/android/maven2/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > dl.google.com

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'https://jcenter.bintray.com/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'https://jcenter.bintray.com/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > jcenter.bintray.com

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > download.flutter.io

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > download.flutter.io

  > Could not resolve io.flutter:arm64_v8a_debug:1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.

     > Could not get resource 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

        > Could not GET 'http://download.flutter.io/io/flutter/arm64_v8a_debug/1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408/arm64_v8a_debug-1.0.0-af51afceb8886cc11e25047523c4e0c7e1f5d408.pom'.

           > download.flutter.io

if anybody knows how to fix it please help.

Body:
> Could not GET 'http://

suggests that your internet is not working as expected. Maybe you are using a vpn? In that case, suspend it for a few minutes. If not, it is another internet related issue...


问:
Laravel Eloquent WhereHas with ORDER column
I have a whereHas query which gets data from a pivot table. But on the pivot table i also have a extra column called 'order' and i use this column to make sure the items are ordered in the correct SEQUENCE as it represents a bus route. Ex: Bus/Ferry stops at 1 2 3 4 5 6.

We have a departure and destination point which are represented as 'port_id'.

So for example the below query gives me the correct data but i need to make sure that the 'order' column is always in the correct sequence based on the departure port id and the arrival port id. So if you would search for port_id 14 to port_id 15 it should not return any results as the 'order' column is not connecting those in that way.

This is what i've tried:

```<code>        $routes = Route::whereHas('ports', function($query) use ($request) {
       $query->where('port_id', $request->route['from']['id']);
    })
    ->whereHas('ports', function($query) use ($request) {
        $query->where('port_id', $request->route['to']['id']);
    })->get();
</code>```

And this is the pivot table:

This is the route table:

Thank you.

答:
i think you could make ordering using join, then ordering the result
by route_id then by 'order' column:

```<code>$routes = Route::whereHas('ports', function($query) use ($request) {
       $query->where('port_id', $request->route['from']['id']);
    })
    ->whereHas('ports', function($query) use ($request) {
        $query->where('port_id', $request->route['to']['id']);
    })
->join('route_port','route_port.route_id','=','routes.id')
->join('ports','route_port.port_id','ports.id')->orderby('route_id')
->orderby('order')->get();
</code>```

please correct the table names if they were wrong ...

Body:
I have a whereHas query which gets data from a pivot table. But on the pivot table i also have a extra column called 'order' and i use this column to make sure the items are ordered in the correct SEQUENCE as it represents a bus route. Ex: Bus/Ferry stops at 1 2 3 4 5 6.

We have a departure and destination point which are represented as 'port_id'.

So for example the below query gives me the correct data but i need to make sure that the 'order' column is always in the correct sequence based on the departure port id and the arrival port id. So if you would search for port_id 14 to port_id 15 it should not return any results as the 'order' column is not connecting those in that way.

This is what i've tried:

        $routes = Route::whereHas('ports', function($query) use ($request) {
       $query->where('port_id', $request->route['from']['id']);
    })
    ->whereHas('ports', function($query) use ($request) {
        $query->where('port_id', $request->route['to']['id']);
    })->get();

And this is the pivot table:

This is the route table:

Thank you.

Body:
i think you could make ordering using join, then ordering the result
by route_id then by 'order' column:

$routes = Route::whereHas('ports', function($query) use ($request) {
       $query->where('port_id', $request->route['from']['id']);
    })
    ->whereHas('ports', function($query) use ($request) {
        $query->where('port_id', $request->route['to']['id']);
    })
->join('route_port','route_port.route_id','=','routes.id')
->join('ports','route_port.port_id','ports.id')->orderby('route_id')
->orderby('order')->get();

please correct the table names if they were wrong ...


问:
in,out,inout,return parameter direction in UML
As i read the following concepts through UML specification promoted by OMG 2.5 (Beta) as:

in: Indicates that Parameter values are passed in by the
  caller.

inout:Indicates that Parameter values are passed in by the caller and then back out to the caller.

out:Indicates that Parameter values are passed out to the caller.

return:Indicates that Parameter values are passed as return values back to the caller.

Does this mean that the "in" is as call by value
and "inout" as call by reference?

could you please clarify each one of those concepts a bit?

答:
Neither "in" means that a parameter is passed by value nor "inout" means that a parameter is passed by reference.

According to clause 13.2.3.2 Behavior Parameters of UML Specification:

When a Behavior is invoked, argument values may be provided corresponding to Parameters with direction “in” or “inout”, as constrained by the multiplicity of those Parameters. ... Argument values are available to affect the course of the invoked Behavior execution

Clause 9.4.3.5 Parameters says:

The effect property may be used to specify what happens to objects passed in or out of a Parameter.

For example "delete" effect means that:

Objects that are values of the parameter do not exist after executions of the behavior are finished.

And then it is explicitly stated that:

Only in and inout Parameters may have a "delete" effect

Pass by value or pass by reference are the implementation methods and both can be used to implement in, inout and out parameters. In C you may pass pointer to function by value and delete the object the pointer points to, if UML model asks you to do so.


问:
unable to perform Iteration with R
I've been practicing with the Titanic dataset and have made steady progress. However, I have got stuck when I try to to replace the missing 'Age' variables with the median age depending upon certain conditions. Here is the dataset:

```<code>| Pclass | Name      |   Sex  | Age |
|:------:|:---------:|:------:|:---:|
|    2   |  officer  |  male  |  NA |
|    3   |  mr       |  male  |  27 |
|    3   |  miss     | female |  NA |
</code>```

Now, I want to replace the NAs with the median ages that i calculated and leave the age already present as it is. For this I used the following code for iteration:

```<code>age_fill <- function(x){

    for (i in length(x$Age)) {

      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }

      else if(is.na(x$Age[i])){

        if (x$Sex[i] == "female" && x$Pclass[i] == "3" && x$Name[i] == "miss"){
          x$Age[i] = 18
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "2" && x$Name[i] == "mr"){
          x$Age[i] = 29
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "3" && x$Name[i] == "officer"){
          x$Age[i] = 25
        }

     }

  }
  return(x)
}
</code>```

The problem here is nothing changes when i run the code as a function or in a loop. However, if I run it separately by putting in the digits of the row, it returns the results just fine.

Can someone pls tell me what I'm doing wrong?

答:
Your Question

Regarding your function there are several issues:

age_fill <- function(x){

    for (i in length(x$Age)) {

      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }
# some more code
}
```

<ol>
<li><p>Your <code>for</code>-loop just loops over one element: <code>length(x$Age)</code> returns one value. I guess you mistook it for <code>1:length(x$Age)</code>.  </p></li>
<li><p>If your function encounters a non-<code>NA</code> value, <code>return(x$Age[i])</code> will break/stop your function and return one value. I don't think that is what you want. In the case of a non-<code>NA</code> value you want your function not to change anything. Therefore you should remove this whole part:</p></li>
</ol>

<pre class="lang-r prettyprint-override"><code>      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }

      else
</code>```

Your condition

if(is.na(x$Age[i])){
# enter code here
}
```

<p>is sufficent.</p>

<h3>Alternative approach</h3>

<p>Here is a solution using <code>dplyr</code>. It's not a direct answer to your question but I want to show you another approach to your problem. Given a dataset</p>

```> df
# A tibble: 6 x 4
  Pclass Name    Sex      Age
   <dbl> <chr>   <chr>  <dbl>
1      2 officer male      NA
2      3 mr      male      27
3      3 miss    female    NA
4      3 mr      male      NA
5      2 mr      male      NA
6      3 officer male      NA
```

<p>that I created with package <code>readr</code></p>

<pre class="lang-r prettyprint-override"><code>df <- read_table2("Pclass  Name        Sex   Age
    2     officer    male    NA
    3     mr         male    27
    3     miss       female   NA
    3     mr         male     NA
    2     mr         male     NA
    3     officer    male     NA")
</code>```

Now we use mutate combined with case_when

df %>%
  mutate(Age = case_when(!is.na(Age) ~ Age,
                         Sex == "male"   & Pclass == "3" & Name == "officer" ~ 25,
                         Sex == "male"   & Pclass == "2" & Name == "mr"      ~ 29,
                         Sex == "female" & Pclass == "3" & Name == "miss"    ~ 18
                        ))
```

<p>which yields</p>

```# A tibble: 6 x 4
  Pclass Name    Sex      Age
   <dbl> <chr>   <chr>  <dbl>
1      2 officer male      NA
2      3 mr      male      27
3      3 miss    female    18
4      3 mr      male      NA
5      2 mr      male      29
6      3 officer male      25
```

Using this approach you don't need a function nor any kind of loop and your conditions are clearly arranged. As a rule of thumb: Try avoiding loops. Usally there are more sophisticated ways of performing a task without loops. R uses "hidden loops" inside functions optimized for performance. However there are tasks well suited for loops. So the decision depends on the actual task.

Title: unable to perform Iteration with R

Body:
I've been practicing with the Titanic dataset and have made steady progress. However, I have got stuck when I try to to replace the missing 'Age' variables with the median age depending upon certain conditions. Here is the dataset:

| Pclass | Name      |   Sex  | Age |
|:------:|:---------:|:------:|:---:|
|    2   |  officer  |  male  |  NA |
|    3   |  mr       |  male  |  27 |
|    3   |  miss     | female |  NA |

Now, I want to replace the NAs with the median ages that i calculated and leave the age already present as it is. For this I used the following code for iteration:

age_fill <- function(x){

    for (i in length(x$Age)) {

      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }

      else if(is.na(x$Age[i])){

        if (x$Sex[i] == "female" && x$Pclass[i] == "3" && x$Name[i] == "miss"){
          x$Age[i] = 18
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "2" && x$Name[i] == "mr"){
          x$Age[i] = 29
        }

        if (x$Sex[i] == "male" && x$Pclass[i] == "3" && x$Name[i] == "officer"){
          x$Age[i] = 25
        }

     }

  }
  return(x)
}

The problem here is nothing changes when i run the code as a function or in a loop. However, if I run it separately by putting in the digits of the row, it returns the results just fine.

Can someone pls tell me what I'm doing wrong?

Body:
Your Question

Regarding your function there are several issues:

age_fill <- function(x){

    for (i in length(x$Age)) {

      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }
# some more code
}

Your for-loop just loops over one element: length(x$Age) returns one value. I guess you mistook it for 1:length(x$Age).

If your function encounters a non-NA value, return(x$Age[i]) will break/stop your function and return one value. I don't think that is what you want. In the case of a non-NA value you want your function not to change anything. Therefore you should remove this whole part:

      if (!is.na(x$Age[i])) {
          return(x$Age[i])

      }

      else

Your condition

if(is.na(x$Age[i])){
# enter code here
}

is sufficent.

Alternative approach

Here is a solution using dplyr. It's not a direct answer to your question but I want to show you another approach to your problem. Given a dataset

> df
# A tibble: 6 x 4
  Pclass Name    Sex      Age
   <dbl> <chr>   <chr>  <dbl>
1      2 officer male      NA
2      3 mr      male      27
3      3 miss    female    NA
4      3 mr      male      NA
5      2 mr      male      NA
6      3 officer male      NA

that I created with package readr

df <- read_table2("Pclass  Name        Sex   Age
    2     officer    male    NA
    3     mr         male    27
    3     miss       female   NA
    3     mr         male     NA
    2     mr         male     NA
    3     officer    male     NA")

Now we use mutate combined with case_when

df %>%
  mutate(Age = case_when(!is.na(Age) ~ Age,
                         Sex == "male"   & Pclass == "3" & Name == "officer" ~ 25,
                         Sex == "male"   & Pclass == "2" & Name == "mr"      ~ 29,
                         Sex == "female" & Pclass == "3" & Name == "miss"    ~ 18
                        ))

which yields

# A tibble: 6 x 4
  Pclass Name    Sex      Age
   <dbl> <chr>   <chr>  <dbl>
1      2 officer male      NA
2      3 mr      male      27
3      3 miss    female    18
4      3 mr      male      NA
5      2 mr      male      29
6      3 officer male      25

Using this approach you don't need a function nor any kind of loop and your conditions are clearly arranged. As a rule of thumb: Try avoiding loops. Usally there are more sophisticated ways of performing a task without loops. R uses "hidden loops" inside functions optimized for performance. However there are tasks well suited for loops. So the decision depends on the actual task.


问:
Null checks on extension methods that do not need an instance?
I recently asked this question on the subject, which was closed as a duplicate of this one - as was this one before mine. However, I want to ask a more specific question on a corner case that I feel none of the above questions, or their answers, really covers:

How should an extension method that doesn't really need an instance react to null references?

An example (where the answer is obvious) would be the .IsNullOrEmpty() (which of course should just return true on a null reference), but I believe there might be other cases where it makes sense to call an extension method on an object that might be null.

Another example could be a variation of the method I outlined in my other question, if we for a minute assume that the foreach loop will not throw on a null collection (I know it does, but imagine it doesn't just as a thought experiment).

What would be best practice here? Should we check for null and throw ArgumentNullException anyway, or does it depend on the case? If it does depend on the case, on what criteria should we decide what to do?

答:
Personally, I have an issue with extension methods that do not throw on a null instance.  I understand that extension methods are syntactic sugar for static methods.  However, their use is like that of an instance method.  Hence, I believe they should behave as if they were an instance method and throw when the "this" instance is null.

This is a maintainability concern for me.  For a newcomer to a code base who does not know whether a method is on the actual type or is an extension method, seeing a method like IsNull() would be disconcerting because it simply doesn't make any sense.

So, that is my two cents: a complete utter personal opinion.


问:
Adding brackets to BETWEEN Query in Laravel?
This is a shortened version of model query:

```<code>User::select('users.*')
    ->when(!empty($this->searchInput['search[term]']), function ($query) {
        return $query->where(
            'biography', 'LIKE', '%' . $this->searchInput['search[term]'] . '%'
        );
    })
    ->when(!empty($this->searchInput['search[location]']), function ($query) {
        return $query->where(
            'country_id',
            $this->searchInput['search[location]']
        );
    })
    ->when(!empty($this->searchInput['engagement']), function ($query) {
        foreach ($this->searchInput['engagement'] as $key => $value) {
            if ($key === array_key_first($this->searchInput['engagement'])) {
                $query->whereBetween('engagement_rate', $value);
            } else {
                $query->orWhereBetween('engagement_rate', $value);
            }
        }
    });
</code>```

(In case you are wondering, I am using $key === array_key_first to ensure the first BETWEEN uses AND, and afterwards uses OR depending on the user's selections)

This equates to the following SQL query:

```<code>SELECT
    `users`.*
FROM
    `users`
WHERE
    `country_id` = '31'
    AND `engagement_rate` BETWEEN '6' AND '20' OR `engagement_rate` BETWEEN '3.5' AND '6'
</code>```

The whereBetween in Eloquent does not include brackets, and as such the country_id selector gets ignored. I need the final SQL statement to be the below (with brackets):

```<code>SELECT
    `users`.*
FROM
    `users`
WHERE
    `country_id` = '31'
    AND (`engagement_rate` BETWEEN '6' AND '20' OR `engagement_rate` BETWEEN '3.5' AND '6')
</code>```

My question:

How can I change my Eloquent query to reflect the above?

答:
Add a parameter group to the whereBetween and orWhereBetween clauses:

```<code>User::select('users.*')
// ...
->when(!empty($this->searchInput['engagement']), function ($query) {

    query->where(function ($q) {
        foreach ($this->searchInput['engagement'] as $key => $value) {
            if ($key === array_key_first($this->searchInput['engagement'])) {
                $q->whereBetween('engagement_rate', $value);
            } else {
                $q->orWhereBetween('engagement_rate', $value);
            }
        }
    });

});
</code>```

Body:
This is a shortened version of model query:

User::select('users.*')
    ->when(!empty($this->searchInput['search[term]']), function ($query) {
        return $query->where(
            'biography', 'LIKE', '%' . $this->searchInput['search[term]'] . '%'
        );
    })
    ->when(!empty($this->searchInput['search[location]']), function ($query) {
        return $query->where(
            'country_id',
            $this->searchInput['search[location]']
        );
    })
    ->when(!empty($this->searchInput['engagement']), function ($query) {
        foreach ($this->searchInput['engagement'] as $key => $value) {
            if ($key === array_key_first($this->searchInput['engagement'])) {
                $query->whereBetween('engagement_rate', $value);
            } else {
                $query->orWhereBetween('engagement_rate', $value);
            }
        }
    });

(In case you are wondering, I am using $key === array_key_first to ensure the first BETWEEN uses AND, and afterwards uses OR depending on the user's selections)

This equates to the following SQL query:

SELECT
    `users`.*
FROM
    `users`
WHERE
    `country_id` = '31'
    AND `engagement_rate` BETWEEN '6' AND '20' OR `engagement_rate` BETWEEN '3.5' AND '6'

The whereBetween in Eloquent does not include brackets, and as such the country_id selector gets ignored. I need the final SQL statement to be the below (with brackets):

SELECT
    `users`.*
FROM
    `users`
WHERE
    `country_id` = '31'
    AND (`engagement_rate` BETWEEN '6' AND '20' OR `engagement_rate` BETWEEN '3.5' AND '6')

My question:

How can I change my Eloquent query to reflect the above?

Body:
Add a parameter group to the whereBetween and orWhereBetween clauses:

User::select('users.*')
// ...
->when(!empty($this->searchInput['engagement']), function ($query) {

    query->where(function ($q) {
        foreach ($this->searchInput['engagement'] as $key => $value) {
            if ($key === array_key_first($this->searchInput['engagement'])) {
                $q->whereBetween('engagement_rate', $value);
            } else {
                $q->orWhereBetween('engagement_rate', $value);
            }
        }
    });

});