问:
simple python port scanner
Can somebody give python 3 based port scanner for a particular ip. For example program will ask ip to be scanned and scan the particular range of open ports in that ip.</p>

答:
It will scan the ips connected in the network. It needs nmap to be installed. Supports Ubuntu.</p>

```<code>from tkinter import *
from tkinter import scrolledtext
import tkinter.messagebox
import datetime
import subprocess
from subprocess import Popen, PIPE
import re
import pandas as pd

df = ()
def ipget():

    i = 'nmap -sP 192.168.1.*'
    output = subprocess.getoutput(i)
    a = str(output).replace("Nmap","").replace("Starting  7.01 ( https://nmap.org ) at","").replace("scan report for","").replace("Host is up","").replace("latency","").replace("done: 256 IP addresses ","")
    a1 = re.sub(r"(\(.*?\)\.)", "", a)
    a2 = re.sub(r'(?m)^\s*', '', a1)
    ms = re.findall(r'\n([^\s]*)\s+\((\d+\.\d+\.\d+\.\d+)\)', a2)
    df = pd.DataFrame(ms, columns=['User', 'IP_Address'])
    txt.insert("end-1c", df)

def searchname(df):

        i = 'nmap -sP 192.168.1.*'
        output = subprocess.getoutput(i)
        a = str(output).replace("Nmap","").replace("Starting  7.01 ( https://nmap.org ) at","").replace("scan report for","").replace("Host is up","").replace("latency","").replace("done: 256 IP addresses ","")
        a1 = re.sub(r"(\(.*?\)\.)", "", a)
        a2 = re.sub(r'(?m)^\s*', '', a1)
        ms = re.findall(r'\n([^\s]*)\s+\((\d+\.\d+\.\d+\.\d+)\)', a2)
        df = pd.DataFrame(ms, columns=['User', 'IP_Address'])
        inputtxt=txt2.get("1.0","end-1c")
        search_data=  (df[df['User'].str.contains(inputtxt)])
        txt.insert("end-1c", search_data)

timestamp = datetime.datetime.now().strftime("%b %d")
window = Tk()
window.title("LAN Checker")
window.geometry('375x270')
Label(window,
        text="IPs Connected in LAN",
        fg = "blue",
        bg = "red",
        font = "Verdana 8 bold").pack()
Label(window,
        text="Day : {}".format(timestamp),
        fg = "red",
        bg = "yellow",
        font = "Verdana 9 bold").pack()
Label(window,
        text="Enter name of person to search his IP",
        fg = "blue",
        bg = "white",
        font = "Verdana 8 bold").pack()
txt2 = scrolledtext.ScrolledText(window,width=20,height=1)
txt2.pack()
txt = scrolledtext.ScrolledText(window,width=50,height=10)
txt.pack()

btn = Button(window, text="Scan all person IPs", command=lambda: ipget(),fg='white',bg="green")
btn.place(x = 180,y = 235)
btn = Button(window, text="Search Person IP", command=lambda: searchname(df),fg='white',bg="blue")
btn.place(x = 15,y = 235)

window.mainloop()
</code>```

Title: simple python port scanner

Body:
It will scan the ips connected in the network. It needs nmap to be installed. Supports Ubuntu.

from tkinter import *
from tkinter import scrolledtext
import tkinter.messagebox
import datetime
import subprocess
from subprocess import Popen, PIPE
import re
import pandas as pd

df = ()
def ipget():

    i = 'nmap -sP 192.168.1.*'
    output = subprocess.getoutput(i)
    a = str(output).replace("Nmap","").replace("Starting  7.01 ( https://nmap.org ) at","").replace("scan report for","").replace("Host is up","").replace("latency","").replace("done: 256 IP addresses ","")
    a1 = re.sub(r"(\(.*?\)\.)", "", a)
    a2 = re.sub(r'(?m)^\s*', '', a1)
    ms = re.findall(r'\n([^\s]*)\s+\((\d+\.\d+\.\d+\.\d+)\)', a2)
    df = pd.DataFrame(ms, columns=['User', 'IP_Address'])
    txt.insert("end-1c", df)

def searchname(df):

        i = 'nmap -sP 192.168.1.*'
        output = subprocess.getoutput(i)
        a = str(output).replace("Nmap","").replace("Starting  7.01 ( https://nmap.org ) at","").replace("scan report for","").replace("Host is up","").replace("latency","").replace("done: 256 IP addresses ","")
        a1 = re.sub(r"(\(.*?\)\.)", "", a)
        a2 = re.sub(r'(?m)^\s*', '', a1)
        ms = re.findall(r'\n([^\s]*)\s+\((\d+\.\d+\.\d+\.\d+)\)', a2)
        df = pd.DataFrame(ms, columns=['User', 'IP_Address'])
        inputtxt=txt2.get("1.0","end-1c")
        search_data=  (df[df['User'].str.contains(inputtxt)])
        txt.insert("end-1c", search_data)

timestamp = datetime.datetime.now().strftime("%b %d")
window = Tk()
window.title("LAN Checker")
window.geometry('375x270')
Label(window,
        text="IPs Connected in LAN",
        fg = "blue",
        bg = "red",
        font = "Verdana 8 bold").pack()
Label(window,
        text="Day : {}".format(timestamp),
        fg = "red",
        bg = "yellow",
        font = "Verdana 9 bold").pack()
Label(window,
        text="Enter name of person to search his IP",
        fg = "blue",
        bg = "white",
        font = "Verdana 8 bold").pack()
txt2 = scrolledtext.ScrolledText(window,width=20,height=1)
txt2.pack()
txt = scrolledtext.ScrolledText(window,width=50,height=10)
txt.pack()

btn = Button(window, text="Scan all person IPs", command=lambda: ipget(),fg='white',bg="green")
btn.place(x = 180,y = 235)
btn = Button(window, text="Search Person IP", command=lambda: searchname(df),fg='white',bg="blue")
btn.place(x = 15,y = 235)

window.mainloop()


来源: stackexchange

问:
How to search in PHP in each columns
I want to search in the database from phpmyadmin, but the resulting search is done in the first column only which mean the result shown the data of the first column only

I tried the below code and the results show only the (college) columns, which is the first column.

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
    <form action="college.php" method="post">
        <select name=type>
            <option vlaue="college">college</option>
            <option vlaue="supervisor">supervisor</option>
            <option value="pro_name">prog_name</option>
        </select>
        <label align='right'>search about</label><br>
        <input type="text" name="valueToSearch">
        <label align='right'>search</label><br>
        <input type="submit" name="search" value="search">
   </form><br><br>
<?php
    if(isset($_POST['search'])) {
        $valueToSearch = $_POST['valueToSearch'];
        $query = "SELECT * FROM `programs` WHERE CONCAT(`college`,
        'supervisor', 'pro_name') LIKE '%".$valueToSearch."%'";
        $search_result = filterTable($query);
    } else {
        $query = "SELECT * FROM `programs`";
        $search_result = filterTable($query);
    }
    // function to connect and execute the query
    function filterTable($query) {
        $connect = mysqli_connect("localhost", "root", "", "IAU");
        $filter_Result = mysqli_query($connect, $query);
        return $filter_Result;
    }
?>
    <table border="1">
        <caption><b>البرامج</b></caption>
        <tr>
            <th align=right>college</th>
            <th align=right>supervisor</th>
            <th align=right>prog_name</th>
        </tr>
        <?php while($row = mysqli_fetch_array($search_result)):?>
        <tr>
            <td align=right><?php echo $row['college'];?></td>
            <td align=right><?php echo $row['supervisor'];?></td>
            <td align=right><?php echo $row['prog_name'];?></td>
        </tr>
        <?php endwhile;?>
    </table>
</body>
</html>
</code>```

the result for the above code is for the first column only
while I want the result for each columns

答:
In your sql

```<code> $query = "SELECT * FROM `programs` WHERE CONCAT(`college`,'supervisor', 'pro_name') LIKE '%".$valueToSearch."%'";
</code>```

only college is interpreted as field name as it has backticks

Supervisor and pro_name are in single quotes. Put all of those in backticks and it should show result correctly.

```<code> $query = "SELECT * FROM `programs` WHERE CONCAT(`college`,`supervisor`, `pro_name`) LIKE '%".$valueToSearch."%'";
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to search in PHP in each columns

Body:
I want to search in the database from phpmyadmin, but the resulting search is done in the first column only which mean the result shown the data of the first column only

I tried the below code and the results show only the (college) columns, which is the first column.

<!DOCTYPE html>

    <form action="college.php" method="post">
        <select name=type>
            <option vlaue="college">college</option>
            <option vlaue="supervisor">supervisor</option>
            <option value="pro_name">prog_name</option>
        </select>
        search about

        <input type="text" name="valueToSearch">
        search

        <input type="submit" name="search" value="search">
   </form>

<?php
    if(isset($_POST['search'])) {
        $valueToSearch = $_POST['valueToSearch'];
        $query = "SELECT * FROM `programs` WHERE CONCAT(`college`,
        'supervisor', 'pro_name') LIKE '%".$valueToSearch."%'";
        $search_result = filterTable($query);
    } else {
        $query = "SELECT * FROM `programs`";
        $search_result = filterTable($query);
    }
    // function to connect and execute the query
    function filterTable($query) {
        $connect = mysqli_connect("localhost", "root", "", "IAU");
        $filter_Result = mysqli_query($connect, $query);
        return $filter_Result;
    }
?>

البرامج

            college
            supervisor
            prog_name

        <?php while($row = mysqli_fetch_array($search_result)):?>

            <?php echo $row['college'];?>
            <?php echo $row['supervisor'];?>
            <?php echo $row['prog_name'];?>

        <?php endwhile;?>

the result for the above code is for the first column only
while I want the result for each columns

Body:
In your sql

 $query = "SELECT * FROM `programs` WHERE CONCAT(`college`,'supervisor', 'pro_name') LIKE '%".$valueToSearch."%'";

only college is interpreted as field name as it has backticks

Supervisor and pro_name are in single quotes. Put all of those in backticks and it should show result correctly.

 $query = "SELECT * FROM `programs` WHERE CONCAT(`college`,`supervisor`, `pro_name`) LIKE '%".$valueToSearch."%'";


问:
iPhone: UIImageView Fades in - Howto?
I have an UIImageView that I want to fade in.

Is there a way to enable that on an underlying UIViewController?

I have translated the simplest answer, though they all work, C# .NET for the MonoTouch users:

```<code>public override void ViewDidAppear (bool animated)
{
    base.ViewDidAppear (animated);
    UIView.BeginAnimations ("fade in");
    UIView.SetAnimationDuration (1);
    imageView.Alpha = 1;
    UIView.CommitAnimations ();
}
</code>```

答:
Change the animation duration to what ever length you want. </p>

```<code>UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage.png"]];
myImageView.center = CGPointMake(100, 100);
myImageView.alpha = 0.0;
[self.view addSubview:myImageView];
[UIView animateWithDuration:5.0 animations:^{
     myImageView.alpha = 1.0;
}];
</code>```

ContentLicense: CC BY-SA 3.0

Title: iPhone: UIImageView Fades in - Howto?

Body:
I have an UIImageView that I want to fade in.

Is there a way to enable that on an underlying UIViewController?

I have translated the simplest answer, though they all work, C# .NET for the MonoTouch users:

public override void ViewDidAppear (bool animated)
{
    base.ViewDidAppear (animated);
    UIView.BeginAnimations ("fade in");
    UIView.SetAnimationDuration (1);
    imageView.Alpha = 1;
    UIView.CommitAnimations ();
}

Body:
Change the animation duration to what ever length you want.

UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage.png"]];
myImageView.center = CGPointMake(100, 100);
myImageView.alpha = 0.0;
[self.view addSubview:myImageView];
[UIView animateWithDuration:5.0 animations:^{
     myImageView.alpha = 1.0;
}];


问:
First time return undefined and second the correct result, how can i fix it?
i have an issue with call on a webservice by using Angular 7. The call is made on this way on my service :

```<code>getLogin(usr: String, pwd: String) {
    return this.http.post("the url of webservice", { username: usr, password: pwd
    });
}
</code>```

and on my component :

```<code> credenzialiConfronto() {
this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value).subscribe((res => {
  this.User = res;
}));

console.log(this.User);
</code>```

why it returns undefined the first time and the second time not?

EDIT :

on my component i try this now but not work :

https://imgur.com/a/LJ5o4HW

and on my service :

https://imgur.com/gUe3sh5

答:
according to this

this should be your service

```<code>/** POST: data to the database */
login(email, password) : Observable<any>{
return this._http.post<any>(this.APIURL+`login`, { email:email, password:password})
.pipe(map(user => {
  return user;
}));
</code>```

}

this should be you component

```<code>   this._loginService.login(this.model.email, this.model.password)
  .subscribe(
    data => {
      this.toast.success(data[constants.MESSAGE]);
    },
    error => {
      this.toast.warning(constants.LOGIN_ERROR);
    });
</code>```

Body:
i have an issue with call on a webservice by using Angular 7. The call is made on this way on my service :

getLogin(usr: String, pwd: String) {
    return this.http.post("the url of webservice", { username: usr, password: pwd
    });
}

and on my component :

 credenzialiConfronto() {
this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value).subscribe((res => {
  this.User = res;
}));

console.log(this.User);

why it returns undefined the first time and the second time not?

EDIT :

on my component i try this now but not work :

https://imgur.com/a/LJ5o4HW

and on my service :

https://imgur.com/gUe3sh5

Body:
according to this

this should be your service

/** POST: data to the database */
login(email, password) : Observable<any>{
return this._http.post<any>(this.APIURL+`login`, { email:email, password:password})
.pipe(map(user => {
  return user;
}));

}

this should be you component

   this._loginService.login(this.model.email, this.model.password)
  .subscribe(
    data => {
      this.toast.success(data[constants.MESSAGE]);
    },
    error => {
      this.toast.warning(constants.LOGIN_ERROR);
    });


问:
Internationalization of Vuetify data table header
I'm trying to internationalize my data table header using Vuetify + I18n.

When I translate my normal code, it works correctly, but now I need to translate the header of my data table built with Vuetify.

I've already tried to add the code this.$vuetify.t('$vuetify.activity.username') or this.$t('$vuetify.activity.username') in the header, but nothing happens. The language stays English (en) always.

Does someone know how to fix it?

I send below my code.

Thank you in advance.

Activity.vue

export default {
  data () {
    return {
      headers: [
        { text: 'ID', value: 'id', width: '1%', align: 'left' },
        { text: this.$vuetify.t('$vuetify.activity.username'), value: 'username', width: '1%' },
        ...
      ]
    }
  },
  ...
}
```

<p><strong>main.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import messages from './assets/lang'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en',
  messages
})

// Vue.use(Vuetify)
Vue.use(Vuetify, {
  lang: {
    t: (key, ...params) => i18n.t(key, params)
  }
})
</code>```

./assets/lang/index.js

module.exports = {
  en: {
    ...
    $vuetify: {
      dataIterator: {
        rowsPerPageText: 'Items per page:',
        ...
      },
      ...
      activity: {
        username: 'Username'
      }
    }
  },
  pt: {
    ...
    $vuetify: {
      dataIterator: {
        rowsPerPageText: 'Itens por página:',
        ...
      },
      ...
      activity: {
        username: 'Nome do usuário'
      }
    }
  }
}
```

答:
You can put your header in a computed function. When the local changes, the headers will be updated</p>

```<code>computed:{

    headers(){
      return [
        { text: 'ID', value: 'id', width: '1%', align: 'left' },
        { text: this.$vuetify.t('$vuetify.activity.username'), value: 'username', width: '1%' },
        ...
      ]
    }
...
}
</code>```

Body:
I'm trying to internationalize my data table header using Vuetify + I18n.

When I translate my normal code, it works correctly, but now I need to translate the header of my data table built with Vuetify.

I've already tried to add the code this.$vuetify.t('$vuetify.activity.username') or this.$t('$vuetify.activity.username') in the header, but nothing happens. The language stays English (en) always.

Does someone know how to fix it?

I send below my code.

Thank you in advance.

Activity.vue

export default {
  data () {
    return {
      headers: [
        { text: 'ID', value: 'id', width: '1%', align: 'left' },
        { text: this.$vuetify.t('$vuetify.activity.username'), value: 'username', width: '1%' },
        ...
      ]
    }
  },
  ...
}

main.js

import messages from './assets/lang'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en',
  messages
})

// Vue.use(Vuetify)
Vue.use(Vuetify, {
  lang: {
    t: (key, ...params) => i18n.t(key, params)
  }
})

./assets/lang/index.js

module.exports = {
  en: {
    ...
    $vuetify: {
      dataIterator: {
        rowsPerPageText: 'Items per page:',
        ...
      },
      ...
      activity: {
        username: 'Username'
      }
    }
  },
  pt: {
    ...
    $vuetify: {
      dataIterator: {
        rowsPerPageText: 'Itens por página:',
        ...
      },
      ...
      activity: {
        username: 'Nome do usuário'
      }
    }
  }
}

Body:
You can put your header in a computed function. When the local changes, the headers will be updated

computed:{

    headers(){
      return [
        { text: 'ID', value: 'id', width: '1%', align: 'left' },
        { text: this.$vuetify.t('$vuetify.activity.username'), value: 'username', width: '1%' },
        ...
      ]
    }
...
}


问:
can't call component constructor that has render function which is returned null in for loop react
I don't know why component constructor doesn't called in for loop
following is my code

```<code>class Marker extends React.Component{
    constructor(pros){
       super(props)
       console.log('test')
    }
    render(){
        null
    }
}

class Map extends React.Component{
    render(){
        <div>{this._renderMarkers()}</div>
    }

    _renderMarkers(){
        this.state.markers.map((item, index)=> {
            return  (
                <div><Marker lat='xx' lng='xx' key={index}/></div>
            )
        }
    }
}
</code>```

when i return just one Marker in _renderMarkers(), i can show that marker constructor is called.

but in for loop, Marker constructor is never called.

how i solved the problem?? give me a good idea plz

答:
Seems like you never return your mapped array in your _renderMarkers function. If the React components are never rendered, their constructors are never called.

```<code>_renderMarkers() {
    return this.state.markers.map((item, index)=> {
        return  (
            <div><Marker lat='xx' lng='xx' key={index}/></div>
        )
    }
}
</code>```

Body:
I don't know why component constructor doesn't called in for loop
following is my code

class Marker extends React.Component{
    constructor(pros){
       super(props)
       console.log('test')
    }
    render(){
        null
    }
}

class Map extends React.Component{
    render(){

{this._renderMarkers()}

    }

    _renderMarkers(){
        this.state.markers.map((item, index)=> {
            return  (

<Marker lat='xx' lng='xx' key={index}/>

            )
        }
    }
}

when i return just one Marker in _renderMarkers(), i can show that marker constructor is called.

but in for loop, Marker constructor is never called.

how i solved the problem?? give me a good idea plz

Body:
Seems like you never return your mapped array in your _renderMarkers function. If the React components are never rendered, their constructors are never called.

_renderMarkers() {
    return this.state.markers.map((item, index)=> {
        return  (
            <div><Marker lat='xx' lng='xx' key={index}/></div>
        )
    }
}


问:
Does the MRTK include animated hand visualizers with grab functionality for use with their VR headsets?
Looking at the sample scenes, it seems like the MRTK uses a pointer system instead of actually giving you virtual hands that can be manipulated by pressing buttons or triggers on the controllers, and allowing you to grab objects.

Is there a built-in way to use hands?

答:
Oculus provide hand models which are rigged in their SDK, which you can appropriate for use in the MRTK as shown in the video below.

https://www.youtube.com/watch?v=F3e2lwqVPyc&list=PLCK8aOPy3e4JhG06GRdlJkmNXoITEewxV&index=4

You'd just need to do a little more work to get the hand rigging hooked up to the MRTK hands.


问:
Upload file to S3 bucket using IAM credentials and policy Java AWS SDK
I'm trying to upload a file to a S3 bucket. First I create an AmazonS3 client using InstanceProfileCredentialsProvider and I get IAM credentials from the instance metadata:

```<code>final AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
    .withCredentials(new InstanceProfileCredentialsProvider(false))
    .withRegion("eu-west-1").build();
</code>```

The role associated to this instance has a policy to access and upload files to a bucket:

```<code>{
    "Version":"2012-10-17",
       "Statement":{
  "Action":[
     "kms:Decrypt",
     "kms:DescribeKey",
     "kms:Encrypt",
     "kms:GenerateDataKey",
     "kms:ReEncryptFrom",
     "kms:ReEncryptTo",
     "s3:GetObject",
     "s3:ListBucket",
     "s3:PutObject*"
  ],
          "Effect":"Allow",
          "Resource":[
          "arn:aws:kms:eu-west-1:[account-id]:key/[key-id]",
          "arn:aws:s3:::[bucket-name]",
          "arn:aws:s3:::[bucket-name]/[path-were-to-save-file]/*"

  ]}}
</code>```

I'm trying to upload the file like this:

```<code>final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file);

s3Client.putObject(request);
</code>```

but I get Access Denied AmazonS3ClientException. Any idea what I am missing?

I also tried to include the kms key to the request:

```<code>final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file)
                .withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("[key-id]"));
</code>```

but it tries to retrieve the key from my account:

```<code>arn:aws:kms:eu-west-1:[my-account-id]:key/[key-id]
</code>```

not the account specified in the policy:

```<code>arn:aws:kms:eu-west-1:[account-id]:key/[key-id]
</code>```

and throws KMSNotFoundException

答:
It seems that I have to specify the full path were I want the file to be saved and I can discard the key:

```<code>final PutObjectRequest request = new PutObjectRequest("[bucket-name]", "[path-were-to-save-file]/" + file.getName(), file);
</code>```

If passing the key is necessary the full arn needs to be supplied not only the key id:

```<code>final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file)
    .withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("arn:aws:kms:eu-west-1:[account-id]:key/[key-id]"));
</code>```

Body:
I'm trying to upload a file to a S3 bucket. First I create an AmazonS3 client using InstanceProfileCredentialsProvider and I get IAM credentials from the instance metadata:

final AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
    .withCredentials(new InstanceProfileCredentialsProvider(false))
    .withRegion("eu-west-1").build();

The role associated to this instance has a policy to access and upload files to a bucket:

{
    "Version":"2012-10-17",
       "Statement":{
  "Action":[
     "kms:Decrypt",
     "kms:DescribeKey",
     "kms:Encrypt",
     "kms:GenerateDataKey",
     "kms:ReEncryptFrom",
     "kms:ReEncryptTo",
     "s3:GetObject",
     "s3:ListBucket",
     "s3:PutObject*"
  ],
          "Effect":"Allow",
          "Resource":[
          "arn:aws:kms:eu-west-1:[account-id]:key/[key-id]",
          "arn:aws:s3:::[bucket-name]",
          "arn:aws:s3:::[bucket-name]/[path-were-to-save-file]/*"

  ]}}

I'm trying to upload the file like this:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file);

s3Client.putObject(request);

but I get Access Denied AmazonS3ClientException. Any idea what I am missing?

I also tried to include the kms key to the request:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file)
                .withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("[key-id]"));

but it tries to retrieve the key from my account:

arn:aws:kms:eu-west-1:[my-account-id]:key/[key-id]

not the account specified in the policy:

arn:aws:kms:eu-west-1:[account-id]:key/[key-id]

and throws KMSNotFoundException

Body:
It seems that I have to specify the full path were I want the file to be saved and I can discard the key:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", "[path-were-to-save-file]/" + file.getName(), file);

If passing the key is necessary the full arn needs to be supplied not only the key id:

final PutObjectRequest request = new PutObjectRequest("[bucket-name]", file.getName(), file)
    .withSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams("arn:aws:kms:eu-west-1:[account-id]:key/[key-id]"));


问:
How to get the "host" object java
I need to get the "host" object of another object. Here an example

Suppose I have the

```<code>class Peer {
    final Service service;
    public Peer(Service service) {
        this.service = service;
    }
    public void ping() {
        service.ping();
    }
}
</code>```

and

```<code>class Service {
    public String hola() {
        this.getPeer()? //HERE I NEED SOME COMMAND TO GET the Peer object, is this possible?
    }
}
</code>```

Then in Service class, I need to get the peer object. Is this possible?

答:
You need to store the Peer object inside your Service object while creating an instance of Service, that's the only way for retrieving it.
Create inside Service a constructor which accepts Peer

```<code>class Service {
    Peer peer;
    public Service(Peer peer){
        this.peer = peer;
    }

    public Peer getPeer() {
        return peer;
    }

    public String hola() {
        Peer peer = getPeer();
    }
}
</code>```

Title: How to get the "host" object java

Body:
I need to get the "host" object of another object. Here an example

Suppose I have the

class Peer {
    final Service service;
    public Peer(Service service) {
        this.service = service;
    }
    public void ping() {
        service.ping();
    }
}

and

class Service {
    public String hola() {
        this.getPeer()? //HERE I NEED SOME COMMAND TO GET the Peer object, is this possible?
    }
}

Then in Service class, I need to get the peer object. Is this possible?

Body:
You need to store the Peer object inside your Service object while creating an instance of Service, that's the only way for retrieving it.
Create inside Service a constructor which accepts Peer

class Service {
    Peer peer;
    public Service(Peer peer){
        this.peer = peer;
    }

    public Peer getPeer() {
        return peer;
    }

    public String hola() {
        Peer peer = getPeer();
    }
}


问:
CollectionView Disappears within StackView (Swift)
I'm trying to achieve the stackView arrangement shown in the middle of this figure:, but for some reason the top stack, containing a collectionView, disappears when using: a .fill distribution

```<code>stackView.distribution = .fill        (stack containing collectionView disappears)
stackView.distribution = .fillEqually (collectionView appears fine in stackView)
</code>```

I've been struggling with this for days, and you'll see residues in my commented out sections: setting compressionResistance/hugging priorities, attempting to change the intrinsic height, changing .layout.itemSize of UICollectionViewFlowLayout(), etc...  Nothing works in my hands. The code here will run if you simply paste it in and associate it with an empty UIViewController. The top, collectionView stack contains a pickerView, and the stacks below that are a pageControllView, subStack of buttons, and a UIView. It all works fine in the .fillEqually distribution, so this is purely a layout issue.  Much Thanks!

```<code>// CodeStackVC2
// Test of programmatically generated stack views
// Output: nested stack views
// To make it run:
// 1) Assign the blank storyboard VC as CodeStackVC2
// 2) Move the "Is Inital VC" arrow to the blank storyboard

import UIKit

class CodeStackVC2: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {

  let fruit = ["Apple", "Orange", "Plum", "Qiwi", "Banana"]
  let veg = ["Lettuce", "Carrot", "Celery", "Onion", "Brocolli"]
  let meat = ["Beef", "Chicken", "Ham", "Lamb"]
  let bread = ["Wheat", "Muffin", "Rye", "Pita"]
  var foods = [[String]]()
  let button = ["bread","fruit","meat","veg"]

  var sView = UIStackView()
  let cellId = "cellId"

  override func viewDidLoad() {
    super.viewDidLoad()
    foods = [fruit, veg, meat, bread]
    setupViews()
  }

  //MARK: Views
  lazy var cView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0
    layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    layout.itemSize = CGSize(width: self.view.frame.width, height: 120)
    let cv = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
     cv.backgroundColor = UIColor.lightGray
    cv.isPagingEnabled = true
    cv.dataSource = self
    cv.delegate = self
    cv.isUserInteractionEnabled = true
    //    var intrinsicContentSize: CGSize {
    //      return CGSize(width: UIViewNoIntrinsicMetric, height: 120)
    //    }
    return cv
  }()

  lazy var pageControl: UIPageControl = {
    let pageC = UIPageControl()
    pageC.numberOfPages = self.foods.count
    pageC.pageIndicatorTintColor = UIColor.darkGray
    pageC.currentPageIndicatorTintColor = UIColor.white
    pageC.backgroundColor = .lightGray
    pageC.addTarget(self, action: #selector(changePage(sender:)), for: UIControlEvents.valueChanged)
//    pageC.setContentHuggingPriority(900, for: .vertical)
//    pageC.setContentCompressionResistancePriority(100, for: .vertical)
    return pageC
  }()

  var readerView: UIView = {
    let rView = UIView()
    rView.backgroundColor = UIColor.brown
//    rView.setContentHuggingPriority(100, for: .vertical)
//    rView.setContentCompressionResistancePriority(900, for: .vertical)
    return rView
  }()

  func makeButton(_ name:String) -> UIButton{
    let newButton = UIButton(type: .system)
    let img = UIImage(named: name)?.withRenderingMode(.alwaysTemplate)
    newButton.setImage(img, for: .normal)
    newButton.contentMode = .scaleAspectFit
    newButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleButton)))
    newButton.isUserInteractionEnabled = true
    newButton.backgroundColor = .orange
    return newButton
  }
  //Make a 4-item vertical stackView containing
  //cView,pageView,subStackof 4-item horiz buttons, readerView
  func setupViews(){
    cView.register(FoodCell.self, forCellWithReuseIdentifier: cellId)
    //generate an array of buttons
    var buttons = [UIButton]()
    for i in 0...foods.count-1 {
      buttons += [makeButton(button[i])]
    }
    let subStackView = UIStackView(arrangedSubviews: buttons)
    subStackView.axis = .horizontal
    subStackView.distribution = .fillEqually
    subStackView.alignment = .center
    subStackView.spacing = 20
    //set up the stackView
    let stackView = UIStackView(arrangedSubviews: [cView,pageControl,subStackView,readerView])
    stackView.axis = .vertical
    //.fillEqually works, .fill deletes cView, .fillProportionally & .equalSpacing delete cView & readerView
    stackView.distribution = .fillEqually
    stackView.alignment = .fill
    stackView.spacing = 5
    //Add the stackView using AutoLayout
    view.addSubview(stackView)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 5).isActive = true
    stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
  }

  func handleButton() {
    print("button pressed")
  }
  //pageControl page changer
  func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * cView.frame.size.width
    cView.setContentOffset(CGPoint(x:x, y:0), animated: true)
  }

  //MARK: horizontally scrolling Chapter collectionView
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    //    let scrollBarLeft = CGFloat(scrollView.contentOffset.x) / CGFloat(book.chap.count + 1)
    //    let scrollBarWidth = CGFloat( menuBar.frame.width) / CGFloat(book.chap.count + 1)
  }

  func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    let index = targetContentOffset.pointee.x / view.frame.width
    pageControl.currentPage = Int(index) //change PageControl indicator
  }

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return foods.count
  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FoodCell
    cell.foodType = foods[indexPath.item]
    return cell
  }

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 120)
  }
}

class FoodCell:UICollectionViewCell, UIPickerViewDelegate, UIPickerViewDataSource {

  var foodType: [String]? {
    didSet {
      pickerView.reloadComponent(0)
      pickerView.selectRow(0, inComponent: 0, animated: true)
    }
  }

  lazy var pickerView: UIPickerView = {
    let pView = UIPickerView()
    pView.frame = CGRect(x:0,y:0,width:Int(pView.bounds.width), height:Int(pView.bounds.height))
    pView.delegate = self
    pView.dataSource = self
    pView.backgroundColor = .darkGray
    return pView
  }()

  override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
  }

  func setupViews() {
    backgroundColor = .clear
    addSubview(pickerView)
    addConstraintsWithFormat("H:|[v0]|", views: pickerView)
    addConstraintsWithFormat("V:|[v0]|", views: pickerView)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
  }

  func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if let count = foodType?.count {
      return count
    } else {
      return 0
    }
  }

  func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let pickerLabel = UILabel()
    pickerLabel.font = UIFont.systemFont(ofSize: 15)
    pickerLabel.textAlignment = .center
    pickerLabel.adjustsFontSizeToFitWidth = true
    if let foodItem = foodType?[row] {
      pickerLabel.text = foodItem
      pickerLabel.textColor = .white
      return pickerLabel
    } else {
      print("chap = nil in viewForRow")
      return UIView()
    }
  }

}
</code>```

答:
Set the top, bottom, leading and trailing constraint of desired controls inside xib or storyboard.

Provide distribution of stack .fill.

Then provide height constraint of all stacks in Xib or storyboard.

Then set appropriate heights for every stacks inside code.

Hopefully it works for you.

Body:
I'm trying to achieve the stackView arrangement shown in the middle of this figure:, but for some reason the top stack, containing a collectionView, disappears when using: a .fill distribution

stackView.distribution = .fill        (stack containing collectionView disappears)
stackView.distribution = .fillEqually (collectionView appears fine in stackView)

I've been struggling with this for days, and you'll see residues in my commented out sections: setting compressionResistance/hugging priorities, attempting to change the intrinsic height, changing .layout.itemSize of UICollectionViewFlowLayout(), etc...  Nothing works in my hands. The code here will run if you simply paste it in and associate it with an empty UIViewController. The top, collectionView stack contains a pickerView, and the stacks below that are a pageControllView, subStack of buttons, and a UIView. It all works fine in the .fillEqually distribution, so this is purely a layout issue.  Much Thanks!

// CodeStackVC2
// Test of programmatically generated stack views
// Output: nested stack views
// To make it run:
// 1) Assign the blank storyboard VC as CodeStackVC2
// 2) Move the "Is Inital VC" arrow to the blank storyboard

import UIKit

class CodeStackVC2: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {

  let fruit = ["Apple", "Orange", "Plum", "Qiwi", "Banana"]
  let veg = ["Lettuce", "Carrot", "Celery", "Onion", "Brocolli"]
  let meat = ["Beef", "Chicken", "Ham", "Lamb"]
  let bread = ["Wheat", "Muffin", "Rye", "Pita"]
  var foods = [[String]]()
  let button = ["bread","fruit","meat","veg"]

  var sView = UIStackView()
  let cellId = "cellId"

  override func viewDidLoad() {
    super.viewDidLoad()
    foods = [fruit, veg, meat, bread]
    setupViews()
  }

  //MARK: Views
  lazy var cView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0
    layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    layout.itemSize = CGSize(width: self.view.frame.width, height: 120)
    let cv = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
     cv.backgroundColor = UIColor.lightGray
    cv.isPagingEnabled = true
    cv.dataSource = self
    cv.delegate = self
    cv.isUserInteractionEnabled = true
    //    var intrinsicContentSize: CGSize {
    //      return CGSize(width: UIViewNoIntrinsicMetric, height: 120)
    //    }
    return cv
  }()

  lazy var pageControl: UIPageControl = {
    let pageC = UIPageControl()
    pageC.numberOfPages = self.foods.count
    pageC.pageIndicatorTintColor = UIColor.darkGray
    pageC.currentPageIndicatorTintColor = UIColor.white
    pageC.backgroundColor = .lightGray
    pageC.addTarget(self, action: #selector(changePage(sender:)), for: UIControlEvents.valueChanged)
//    pageC.setContentHuggingPriority(900, for: .vertical)
//    pageC.setContentCompressionResistancePriority(100, for: .vertical)
    return pageC
  }()

  var readerView: UIView = {
    let rView = UIView()
    rView.backgroundColor = UIColor.brown
//    rView.setContentHuggingPriority(100, for: .vertical)
//    rView.setContentCompressionResistancePriority(900, for: .vertical)
    return rView
  }()

  func makeButton(_ name:String) -> UIButton{
    let newButton = UIButton(type: .system)
    let img = UIImage(named: name)?.withRenderingMode(.alwaysTemplate)
    newButton.setImage(img, for: .normal)
    newButton.contentMode = .scaleAspectFit
    newButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleButton)))
    newButton.isUserInteractionEnabled = true
    newButton.backgroundColor = .orange
    return newButton
  }
  //Make a 4-item vertical stackView containing
  //cView,pageView,subStackof 4-item horiz buttons, readerView
  func setupViews(){
    cView.register(FoodCell.self, forCellWithReuseIdentifier: cellId)
    //generate an array of buttons
    var buttons = [UIButton]()
    for i in 0...foods.count-1 {
      buttons += [makeButton(button[i])]
    }
    let subStackView = UIStackView(arrangedSubviews: buttons)
    subStackView.axis = .horizontal
    subStackView.distribution = .fillEqually
    subStackView.alignment = .center
    subStackView.spacing = 20
    //set up the stackView
    let stackView = UIStackView(arrangedSubviews: [cView,pageControl,subStackView,readerView])
    stackView.axis = .vertical
    //.fillEqually works, .fill deletes cView, .fillProportionally & .equalSpacing delete cView & readerView
    stackView.distribution = .fillEqually
    stackView.alignment = .fill
    stackView.spacing = 5
    //Add the stackView using AutoLayout
    view.addSubview(stackView)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 5).isActive = true
    stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
  }

  func handleButton() {
    print("button pressed")
  }
  //pageControl page changer
  func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * cView.frame.size.width
    cView.setContentOffset(CGPoint(x:x, y:0), animated: true)
  }

  //MARK: horizontally scrolling Chapter collectionView
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    //    let scrollBarLeft = CGFloat(scrollView.contentOffset.x) / CGFloat(book.chap.count + 1)
    //    let scrollBarWidth = CGFloat( menuBar.frame.width) / CGFloat(book.chap.count + 1)
  }

  func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    let index = targetContentOffset.pointee.x / view.frame.width
    pageControl.currentPage = Int(index) //change PageControl indicator
  }

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return foods.count
  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FoodCell
    cell.foodType = foods[indexPath.item]
    return cell
  }

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 120)
  }
}

class FoodCell:UICollectionViewCell, UIPickerViewDelegate, UIPickerViewDataSource {

  var foodType: [String]? {
    didSet {
      pickerView.reloadComponent(0)
      pickerView.selectRow(0, inComponent: 0, animated: true)
    }
  }

  lazy var pickerView: UIPickerView = {
    let pView = UIPickerView()
    pView.frame = CGRect(x:0,y:0,width:Int(pView.bounds.width), height:Int(pView.bounds.height))
    pView.delegate = self
    pView.dataSource = self
    pView.backgroundColor = .darkGray
    return pView
  }()

  override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
  }

  func setupViews() {
    backgroundColor = .clear
    addSubview(pickerView)
    addConstraintsWithFormat("H:|[v0]|", views: pickerView)
    addConstraintsWithFormat("V:|[v0]|", views: pickerView)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
  }

  func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if let count = foodType?.count {
      return count
    } else {
      return 0
    }
  }

  func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let pickerLabel = UILabel()
    pickerLabel.font = UIFont.systemFont(ofSize: 15)
    pickerLabel.textAlignment = .center
    pickerLabel.adjustsFontSizeToFitWidth = true
    if let foodItem = foodType?[row] {
      pickerLabel.text = foodItem
      pickerLabel.textColor = .white
      return pickerLabel
    } else {
      print("chap = nil in viewForRow")
      return UIView()
    }
  }

}


问:
Automatically execute Sphinx on Python script using Jenkins
I have been trying to create a Jenkins job that automatically executes a python script and launch its documentation via Sphinx.

The execution part works well but I'm not able to do the Sphinx part. My first idea was to create an 'Execute Windows Script bash' step inside the Jenkins job with make html command after going to the right directory with cd. But I keep on getting this error:

```<code>make is not recognized as an internal or external command
</code>```

Same idea works when I do it from the CMD tool.
I already added the PATH variable in Jenkins settings with System32 folder.

System Information:

OS: Windows

Arch: x64

答:
I figured out, I just had to put the following inside my Windows Shell Job:</p>

```<code>call "Path\To\make.bat"
</code>```

Body:
I have been trying to create a Jenkins job that automatically executes a python script and launch its documentation via Sphinx.

The execution part works well but I'm not able to do the Sphinx part. My first idea was to create an 'Execute Windows Script bash' step inside the Jenkins job with make html command after going to the right directory with cd. But I keep on getting this error:

make is not recognized as an internal or external command

Same idea works when I do it from the CMD tool.
I already added the PATH variable in Jenkins settings with System32 folder.

System Information:

OS: Windows

Arch: x64

Body:
I figured out, I just had to put the following inside my Windows Shell Job:

call "Path\To\make.bat"


问:
Div height according to content
I am working on a Modal with fixed header and footer.

Here is the Jsfiddle example

Currently the scrollable-stuff class height is 80%. If the content is less and there is no scrolling then i need to reduce the height and take the height of the content.

For example this example has a less content and there is no scroller but there is a empty space. I need to take the height of the content in case if there is no scrolling.

Any help or suggestion would be appreciated

Thanks in advace.

答:
In these cases I love to take advantage of the flexbox column direction. The idea here is to have fixed heights for the footer and the header and then make the content take the rest with flex-basis: 100% and flex-grow: 1.

First of all remove the inline styling style="width:600px;height:300px as it is conflicting with this solution, then add a class to your modal. For the example below I chose "myModal", and as a side note, use overflow: auto, to avoid scrollbars where there isn't enough content. This solution is also handling the default styling that comes with fancybox.

Example

$(document).ready(function() {

   $("#ModalPopup").fancybox({}).trigger('click');

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.title-div {
  min-height: 32px;
}

.scrollable-stuff {
  overflow-y: auto;
  flex-grow: 1;
  flex-basis: 100%;
}

.button-div {
  min-height: 32px;
}

.myModal {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet"/>

Title

For Your Information

Here is some text to fill out this space.

Here is some text to fill out this space.

Here is some text to fill out this space.

Here is some text to fill out this space.

Here is some text to fill out this space.

Here is some text to fill out this space.

Here is some text to fill out this space.

Here is some text to fill out this space.

Here is some text to fill out this space.

    <button type="button" class="btn-primary">Click</button>

```

Title: Div height according to content

Body:
In these cases I love to take advantage of the flexbox column direction. The idea here is to have fixed heights for the footer and the header and then make the content take the rest with flex-basis: 100% and flex-grow: 1.

First of all remove the inline styling style="width:600px;height:300px as it is conflicting with this solution, then add a class to your modal. For the example below I chose "myModal", and as a side note, use overflow: auto, to avoid scrollbars where there isn't enough content. This solution is also handling the default styling that comes with fancybox.

Example

$(document).ready(function() {

   $("#ModalPopup").fancybox({}).trigger('click');

});

.title-div {
  min-height: 32px;
}

.scrollable-stuff {
  overflow-y: auto;
  flex-grow: 1;
  flex-basis: 100%;
}

.button-div {
  min-height: 32px;
}

.myModal {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>

<div id="ModalPopup" class="myModal">

  <div class="title-div">Title</div>

  <div class="scrollable-stuff">

    <h1>For Your Information</h1>

    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
    <p>Here is some text to fill out this space.</p>
  </div>

  <div class="button-div">
    <button type="button" class="btn-primary">Click</button>
  </div>
</div>


问:
How to pass an array from an api as props to another component
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

```<code>     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}><i className="fa fa-search"></i></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}
</code>```

--------------------------------SearchedUser Component------------------------

```<code>    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

    render(){
console.log(this.state.Name);
return(
    <div>
    </div>
     )
    }
    }
export default SearchedUser;
</code>```

答:
Can you try
console.log(this.props.UserName);
inside the render() in SearchedUser Component.

Because you are trying to get the username from the constructor and by default the search component will be getting null value in the props.username

The props.username will only get the new value only after the fetch response has been received.

Body:
I am making an api call which returns me an array of Usernames. I am calling the api in a Navbar component and am sending the data returned by the api to another component as props. When I console.log(this.state.Name) in Navbar it gives the whole array having usernames in the console, but when i receive the array in the other SearchedUser componenet and console.log() the recieved prop it gives me undefined in the console. Can Anyone tell whats wrong.

----------------------------------Navbar Component----------------------------

     class Navbar extends Component{

     constructor(props){
    super(props);
    this.state={
        name:'',
        Name:[],
    }
     this.GetUserData=this.GetUserData.bind(this);
}

    GetUserData=()=>{
fetch(`http://localhost:4000/data/searchuser?Name=${this.state.name}`)
.then(response => response.json())
.then(data=> this.setState({Name:data.datad}))
.catch(err=>console.log(err));}

        render()
{
    console.log(this.state.Name);
    return(
        <Router>
          <Link to={'/SearchedUser'}>
                <button type="submit" onClick={this.GetUserData}></button>
         </Link>
            <Switch>
                <Route exact path='/' component={HomeContent} />
                <Route path='/Profile' component={Profile}/>
                <Route path='/SearchedUser' render={(props)=> <SearchedUser {...props} UserName={ [this.state.Name]}/>}/>
            </Switch>
        </Router>)  }}

--------------------------------SearchedUser Component------------------------

    import React from 'react'
class SearchedUser extends React.Component{
constructor(props){
super(props);
this.state={
    Name: props.UserName
}
    }

    render(){
console.log(this.state.Name);
return(

     )
    }
    }
export default SearchedUser;


答:
Initially set the alpha of your imageview as 0 as imageView.alpha = 0;

```<code>- (void)fadeInImage
{
[UIView beginAnimations:@"fade in" context:nil];
    [UIView setAnimationDuration:1.0];
    imageView.alpha = 1.0;
    [UIView commitAnimations];

}
</code>```

Title: iPhone: UIImageView Fades in - Howto?

Body:
I have an UIImageView that I want to fade in.

Is there a way to enable that on an underlying UIViewController?

I have translated the simplest answer, though they all work, C# .NET for the MonoTouch users:

public override void ViewDidAppear (bool animated)
{
    base.ViewDidAppear (animated);
    UIView.BeginAnimations ("fade in");
    UIView.SetAnimationDuration (1);
    imageView.Alpha = 1;
    UIView.CommitAnimations ();
}

Body:
Initially set the alpha of your imageview as 0 as imageView.alpha = 0;

- (void)fadeInImage
{
[UIView beginAnimations:@"fade in" context:nil];
    [UIView setAnimationDuration:1.0];
    imageView.alpha = 1.0;
    [UIView commitAnimations];

}


问:
Interrupt a Python function and manipulate the variables
I have the file main.py containing the code

```<code>def my_function():

    a = 0
    b = 1
    c = 2

if __name__ == "__main__":
    my_function()
</code>```

I execute this script from a terminal / shell.

If I run the script with python -i main.py all the variables are already gone because the function my_function has ran out of scope.

How do I interrupt the running of the script after the command a = 0 and set a to the value 1?

EDIT
My goal with this question is to learn how I can apply some commands on variables that are the result of a function, even after the function has finished. So the code I wrote above is just a (minimum working) example.

答:
You can use Python debuger's set_trace() to break into the debugger from a running program and manipulate variables.
Use debugger command c(ont(inue)) to continue execution.

```<code>def my_function():

    a = 0
    import pdb
    pdb.set_trace()
    b = 1
    c = 2

if __name__ == "__main__":
    my_function()
</code>```

Body:
I have the file main.py containing the code

def my_function():

    a = 0
    b = 1
    c = 2

if __name__ == "__main__":
    my_function()

I execute this script from a terminal / shell.

If I run the script with python -i main.py all the variables are already gone because the function my_function has ran out of scope.

How do I interrupt the running of the script after the command a = 0 and set a to the value 1?

EDIT
My goal with this question is to learn how I can apply some commands on variables that are the result of a function, even after the function has finished. So the code I wrote above is just a (minimum working) example.

Body:
You can use Python debuger's set_trace() to break into the debugger from a running program and manipulate variables.
Use debugger command c(ont(inue)) to continue execution.

def my_function():

    a = 0
    import pdb
    pdb.set_trace()
    b = 1
    c = 2

if __name__ == "__main__":
    my_function()


问:
(Microsoft Azure custom vision service: Object Detection) How to find bounding box info of training data?
I am using Microsoft custom vision service in object detection to extract the wanted objects. And I would like to make a regression test to compare the results. However, I cannot find a place to export the training picture with the bounding box that user defined by GUI.

The model training is done within the custom vision platform provided by Microsoft (https://www.customvision.ai/). Within this platform we can add the images and then tag the objects. I have tried to export the model, but I am not sure where to find the info of training pictures along with their tag(s) and bounding box(es).

I expect that in this platform, user can export the not only the trained model but also the training data (images with tags and bounding boxes.) But I was not able to find them.

答: Please see the following link for export your model. Custom Vision Service exports compact domains. The models generated by compact domains are optimized for the constraints of real-time classification on mobile devices. If the user wants to export the user training data from the custom vision please see the following link. </p>


问:
Is there an approach which can delay certain seconds between every function call which need to update ui components?
I am writing a maze game, and one of its features is "Show solution". The solution may contain many steps, I am using a for loop to iterate every step, in order to show it clear to a player, I wish it can pause one second around after every step. I know the delay operation cannot be put in UI thread, so I have tried several async delay approach. Unfortunately, because of its async nature, if the solution has more than one step, the UI cannot update till the last step finish. That's not I want certainly.

I have tried handler.postDelayed approach, new Timer().schedule approach.

    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        for(int[] step: solution) {
            ImageView v = (ImageView)findViewById(viewIdList[step[0]][step[1]]);
            setTimeout(() -> {v.callOnClick();}, 1);
        }
    }

    private void setTimeout(Runnable r, int seconds) {
        Handler handler = new Handler();
        handler.postDelayed(r, seconds * 1000);
    }
```

<p>Maybe a synchronous delay approach is what I need, and it must not block the ui update.</p>

<p>update: CountDownTimer is suitable for this situation. In fact, I have seen a CountDownTime answer at other questions, I should have tried that approach first before I ask. Thank you all who have given a response.  Here's my final code:</p>

<pre class="lang-java prettyprint-override"><code>    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        int stepTotal = solution.length;
        int stepPause = 1000;
        int timeTotal = (stepTotal + 1) * stepPause;

        new CountDownTimer(timeTotal, stepPause) {
            int stepIndex = 0;
            public void onTick(long timeRemain) {
                int[] pos = solution[stepIndex];
                ImageView v = (ImageView)findViewById(viewIdList[pos[0]][pos[1]]);
                v.callOnClick();
                stepIndex += 1;
                Log.d("time remain:", "" + timeRemain / 1000);
            }

            public void onFinish() {
                Log.d("final step", ":" + (stepIndex - 1));
            }
        }.start();
    }
</code>```

答:
Try something like this,</p>

```<code>public void showSolution(View view) {
// Do something long
Runnable runnable = new Runnable() {
    @Override
    public void run() {
int stage = currentGame.currentStage;
    int[][] solution = GameMap.solutionList[stage];
    drawStage(stage);
    for(int[] step: solution) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                       ImageView v = (ImageView)findViewById(viewIdList[step[0]][step[1]]);
        setTimeout(() -> {v.callOnClick();}, 1);
                }
            });
        }
    }
};
new Thread(runnable).start();
}
</code>```

Body:
I am writing a maze game, and one of its features is "Show solution". The solution may contain many steps, I am using a for loop to iterate every step, in order to show it clear to a player, I wish it can pause one second around after every step. I know the delay operation cannot be put in UI thread, so I have tried several async delay approach. Unfortunately, because of its async nature, if the solution has more than one step, the UI cannot update till the last step finish. That's not I want certainly.

I have tried handler.postDelayed approach, new Timer().schedule approach.

    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        for(int[] step: solution) {
            ImageView v = (ImageView)findViewById(viewIdList[step[0]][step[1]]);
            setTimeout(() -> {v.callOnClick();}, 1);
        }
    }

    private void setTimeout(Runnable r, int seconds) {
        Handler handler = new Handler();
        handler.postDelayed(r, seconds * 1000);
    }

Maybe a synchronous delay approach is what I need, and it must not block the ui update.

update: CountDownTimer is suitable for this situation. In fact, I have seen a CountDownTime answer at other questions, I should have tried that approach first before I ask. Thank you all who have given a response.  Here's my final code:

    public void showSolutionClick(View view) {
        int stage = currentGame.currentStage;
        int[][] solution = GameMap.solutionList[stage];
        drawStage(stage);
        int stepTotal = solution.length;
        int stepPause = 1000;
        int timeTotal = (stepTotal + 1) * stepPause;

        new CountDownTimer(timeTotal, stepPause) {
            int stepIndex = 0;
            public void onTick(long timeRemain) {
                int[] pos = solution[stepIndex];
                ImageView v = (ImageView)findViewById(viewIdList[pos[0]][pos[1]]);
                v.callOnClick();
                stepIndex += 1;
                Log.d("time remain:", "" + timeRemain / 1000);
            }

            public void onFinish() {
                Log.d("final step", ":" + (stepIndex - 1));
            }
        }.start();
    }

Body:
Try something like this,

public void showSolution(View view) {
// Do something long
Runnable runnable = new Runnable() {
    @Override
    public void run() {
int stage = currentGame.currentStage;
    int[][] solution = GameMap.solutionList[stage];
    drawStage(stage);
    for(int[] step: solution) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                       ImageView v = (ImageView)findViewById(viewIdList[step[0]][step[1]]);
        setTimeout(() -> {v.callOnClick();}, 1);
                }
            });
        }
    }
};
new Thread(runnable).start();
}


问:
Initializing a subclass with an existing superclass instance in python3
I am writing my own version of the socket class in python.
I was wondering if there is a way to not initialize the subclass using it's __init__ method, but rather initialize it using an existing instance of the socket class.

Basically, what I am trying to do, is inherit from the socket class, and overwrite the accept() method to return an object of my own class instead of the socket class.

To get around this problem I want to implement the possibility to set a base socket in my __init__ method in my custom socket class, which takes the instance of a socket as argument and creates a new instance of my custom socket class using an existing instance of the socket class, or do the same using a fromSocket() classmethod.

My question now is how do I set an existing instance of the socket class as superclass for my own socket without using an attribute to contain the socket object? (Is that even possible in python?)

All the other related questions I found were more on how to change a superclass at runtime. I may have overlooked the answer somewhere, but I couldn't find it.

My code looks something like this:

```<code>import socket
class MySocket(socket.socket):
    def __init__(self, sock:socket.socket=None):
        if sock != None:
            # initialize using existing instance contained in sock
            # How? (My question)
        else:
            super().__init__() # Default conf is enough for now
    def accept(self):
        s, addr = super().accept()
        return MySocket(sock=s) # <= This is what I want to do
</code>```

and I want to call it like this:

```<code>s = MySocket()
# Call bind and listen, left out because it doesn't matter here
client, addr = s.accept()
# Client is an instance of socket.socket, but it should be MySocket
</code>```

答:
Here's the source code for socket.accept().

Honestly, this looks like a mistake on the socket class, they've hardcoded it to create a new instance of socket:

```<code>sock = socket(self.family, self.type, self.proto, fileno=fd)
</code>```

When it probably should fetch the type of self instead:

```<code>sock = type(self)(self.family, self.type, self.proto, fileno=fd)
</code>```

This seems to be done in multiple methods, it looks like your best chance is to copy all the attributes manually from the returned socket to your custom instance. The dup() method is hopefully correct, so we can create a classmethod that repeats its functionality:

```<code>import socket

class MySocket(socket.socket):
    @classmethod
    def from_socket(cls, sock):
        fd = socket.dup(sock.fileno())
        my_sock = cls(sock.family, sock.type, sock.proto, fileno=fd)
        my_sock.settimeout(sock.gettimeout())
        return my_sock
</code>```

Body:
I am writing my own version of the socket class in python.
I was wondering if there is a way to not initialize the subclass using it's __init__ method, but rather initialize it using an existing instance of the socket class.

Basically, what I am trying to do, is inherit from the socket class, and overwrite the accept() method to return an object of my own class instead of the socket class.

To get around this problem I want to implement the possibility to set a base socket in my __init__ method in my custom socket class, which takes the instance of a socket as argument and creates a new instance of my custom socket class using an existing instance of the socket class, or do the same using a fromSocket() classmethod.

My question now is how do I set an existing instance of the socket class as superclass for my own socket without using an attribute to contain the socket object? (Is that even possible in python?)

All the other related questions I found were more on how to change a superclass at runtime. I may have overlooked the answer somewhere, but I couldn't find it.

My code looks something like this:

import socket
class MySocket(socket.socket):
    def __init__(self, sock:socket.socket=None):
        if sock != None:
            # initialize using existing instance contained in sock
            # How? (My question)
        else:
            super().__init__() # Default conf is enough for now
    def accept(self):
        s, addr = super().accept()
        return MySocket(sock=s) # <= This is what I want to do

and I want to call it like this:

s = MySocket()
# Call bind and listen, left out because it doesn't matter here
client, addr = s.accept()
# Client is an instance of socket.socket, but it should be MySocket

Body:
Here's the source code for socket.accept().

Honestly, this looks like a mistake on the socket class, they've hardcoded it to create a new instance of socket:

sock = socket(self.family, self.type, self.proto, fileno=fd)

When it probably should fetch the type of self instead:

sock = type(self)(self.family, self.type, self.proto, fileno=fd)

This seems to be done in multiple methods, it looks like your best chance is to copy all the attributes manually from the returned socket to your custom instance. The dup() method is hopefully correct, so we can create a classmethod that repeats its functionality:

import socket

class MySocket(socket.socket):
    @classmethod
    def from_socket(cls, sock):
        fd = socket.dup(sock.fileno())
        my_sock = cls(sock.family, sock.type, sock.proto, fileno=fd)
        my_sock.settimeout(sock.gettimeout())
        return my_sock


问:
How to call function that uses hooks in typescript?
Im trying to add typescript(im of course new to that) to my react project. I wrote a hook that fetches data from api that i wrote. I want to add typings but typescript won't compile I think because of undefined state at the beginning of rendering. I'm guessing. The problem is with calling a formatData function inside VictoryPie component.The rror that i get:

```<code>TypeScript error: Argument of type 'boolean | never[]' is not assignable to parameter of type 'Data[]'.
  Type 'false' is not assignable to type 'Data[]'.  TS2345

    26 |         <VictoryPie
    27 |           colorScale={['tomato', 'orange', 'gold', 'cyan', 'navy']}
  > 28 |           data={formatData(graphData)}
       |                            ^
    29 |           x="description"
    30 |           y="amount"
    31 |         />
</code>```

```<code>import React from 'react';
import {useFetch} from '../hooks';
import {VictoryPie} from 'victory';

interface Data {
  _id: number,
  id: string,
  userName: string,
  amount: number,
  description: string,
  time: string,
}

const Graph = () => {
  const [graphData, loading] = useFetch('/api/Kamil');
  const formatData = (inputData: Array<Data>) => {
    return inputData.map(
      ({_id, id, time, userName, ...keepAttrs}) => keepAttrs,
    );
  };
  return (
    <>
      {loading ? (
        'Loading...'
      ) : (
        <VictoryPie
          colorScale={['tomato', 'orange', 'gold', 'cyan', 'navy']}
          data={formatData(graphData)}
          x="description"
          y="amount"
        />
      )}
    </>
  );
};
export default Graph;
</code>```

Hook

```<code>import {useState, useEffect} from 'react';
import axios from 'axios';

function useFetch(url: string) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  async function fetchUrl() {
    const response = await axios(url);
    console.log(response);
    setData(response.data)
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  }, []);
  return [data, loading];
}
export { useFetch };
</code>```

答:
There are 2 issues here.

You need to declare that your hook returns tuple. Now typescript assumes you're returning array of data and loading in any order.

Also you need to declare what kind of result do you expect as fetch result.

Your hook should look something like

```<code>function useFetch<ExpectedResult>(url: string, initialData: ExpectedResult): [ExpectedResult, boolean] {
  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await axios(url);
    console.log(response);
    setData(response.data)
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  }, [url]); // <<-- when url is changed you propably want to re-fetch
  return [data, loading];
}
</code>```

and then when you use it

do it like

```<code>type DataFromServer = Date[];

const [data, isLoading] = useFetch<DataFromServer>('/api/Kamil', []);
</code>```

Now typescript knows what [data, isLoading] are supposed to be.

Body:
Im trying to add typescript(im of course new to that) to my react project. I wrote a hook that fetches data from api that i wrote. I want to add typings but typescript won't compile I think because of undefined state at the beginning of rendering. I'm guessing. The problem is with calling a formatData function inside VictoryPie component.The rror that i get:

TypeScript error: Argument of type 'boolean | never[]' is not assignable to parameter of type 'Data[]'.
  Type 'false' is not assignable to type 'Data[]'.  TS2345

    26 |         <VictoryPie
    27 |           colorScale={['tomato', 'orange', 'gold', 'cyan', 'navy']}
  > 28 |           data={formatData(graphData)}
       |                            ^
    29 |           x="description"
    30 |           y="amount"
    31 |         />

import React from 'react';
import {useFetch} from '../hooks';
import {VictoryPie} from 'victory';

interface Data {
  _id: number,
  id: string,
  userName: string,
  amount: number,
  description: string,
  time: string,
}

const Graph = () => {
  const [graphData, loading] = useFetch('/api/Kamil');
  const formatData = (inputData: Array<Data>) => {
    return inputData.map(
      ({_id, id, time, userName, ...keepAttrs}) => keepAttrs,
    );
  };
  return (
    <>
      {loading ? (
        'Loading...'
      ) : (
        <VictoryPie
          colorScale={['tomato', 'orange', 'gold', 'cyan', 'navy']}
          data={formatData(graphData)}
          x="description"
          y="amount"
        />
      )}
    </>
  );
};
export default Graph;

Hook

import {useState, useEffect} from 'react';
import axios from 'axios';

function useFetch(url: string) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  async function fetchUrl() {
    const response = await axios(url);
    console.log(response);
    setData(response.data)
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  }, []);
  return [data, loading];
}
export { useFetch };

Body:
There are 2 issues here.

You need to declare that your hook returns tuple. Now typescript assumes you're returning array of data and loading in any order.

Also you need to declare what kind of result do you expect as fetch result.

Your hook should look something like

function useFetch<ExpectedResult>(url: string, initialData: ExpectedResult): [ExpectedResult, boolean] {
  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(true);

  async function fetchUrl() {
    const response = await axios(url);
    console.log(response);
    setData(response.data)
    setLoading(false);
  }
  useEffect(() => {
    fetchUrl();
  }, [url]); // <<-- when url is changed you propably want to re-fetch
  return [data, loading];
}

and then when you use it

do it like

type DataFromServer = Date[];

const [data, isLoading] = useFetch<DataFromServer>('/api/Kamil', []);

Now typescript knows what [data, isLoading] are supposed to be.


问:
Rename property with Gremlin in Azure Cosmos DB
Some of our codebase has changed, so it now expects the vertices that used to have a property with the name "Sdg" to now have a property with the name "causeType" and with the same value instead.... In short, a renaming of the property.

I have tried quite a bit at this point, and... Am a bit surprised of how hard it has been to figure out how to search the graph, and do a renaming when needed.

The closest I have come is the following query:

```<code>g.V().has('sdg').as('vertexWithOldProperty').property('causeType', value(select('vertexWithOldProperty').select('sdg')))
</code>```

...It does not work due to the error:

Gremlin Query Compilation Error: Unable to bind to method 'value',
  with arguments of type: (GraphTraversal) @ line 1, column 68.  Unable
  to bind to method 'property', with arguments of type: (String)

The idea was to run over the graph and remember every vertice that had the old value. Then I would add the new property with the same value to them... And for simplicity/feasibility I decided to just ignore the old value instead of removing it.

Can anyone help me or lead me in the right direction?

Thanks!

答:
Maybe there's a better way, but I think this should work for you:

```<code>g.V().has('sdg').property('causeType', values('sdg'))

</code>```

And if you want to delete the old property

```<code>g.V().has('sdg').property('causeType', values('sdg')).properties('sdg').drop()

</code>```

Body:
Some of our codebase has changed, so it now expects the vertices that used to have a property with the name "Sdg" to now have a property with the name "causeType" and with the same value instead.... In short, a renaming of the property.

I have tried quite a bit at this point, and... Am a bit surprised of how hard it has been to figure out how to search the graph, and do a renaming when needed.

The closest I have come is the following query:

g.V().has('sdg').as('vertexWithOldProperty').property('causeType', value(select('vertexWithOldProperty').select('sdg')))

...It does not work due to the error:

Gremlin Query Compilation Error: Unable to bind to method 'value',
  with arguments of type: (GraphTraversal) @ line 1, column 68.  Unable
  to bind to method 'property', with arguments of type: (String)

The idea was to run over the graph and remember every vertice that had the old value. Then I would add the new property with the same value to them... And for simplicity/feasibility I decided to just ignore the old value instead of removing it.

Can anyone help me or lead me in the right direction?

Thanks!

Body:
Maybe there's a better way, but I think this should work for you:

g.V().has('sdg').property('causeType', values('sdg'))

And if you want to delete the old property

g.V().has('sdg').property('causeType', values('sdg')).properties('sdg').drop()


问:
jQuery - exclude inputs with certain value from selector
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

```<code>$('#mydiv input:not(val("100")').val(myvariable);
</code>```

how to do that, is it possible in simple selector?
thanks

答:
```<code>var n = jQuery("input[value!='1']").val();

alert(n);
</code>```

check this link too

http://api.jquery.com/attribute-not-equal-selector/

Body:
I would like to select all inputs in my div and set them new value but also I want to exclude inputs with certain value
something like this:

$('#mydiv input:not(val("100")').val(myvariable);

how to do that, is it possible in simple selector?
thanks

Body:
var n = jQuery("input[value!='1']").val();

alert(n);

check this link too

http://api.jquery.com/attribute-not-equal-selector/


问:
what's the 'sort' method's difference between chrome environment and node environment
I found the sort method shows different behavior between in Chrome environment and in the node environment

const arr = ['l', 'h', 'z', 'b', 's'];
arr.sort((pre, next) => {
    return pre < next;
});
console.log(arr);
```

the node environment's result is [ 'z', 's', 'l', 'h', 'b' ], it's sorted.

the chrome console environment's result is ['l', 'h', 'z', 'b', 's'], nothing changed.

chrome's result is what I expect, I don't understand why it working in node environment.

chrome version is 74.0.3729.169 X64

node vsrions is v10.12.0.

答:
V8 developer here.

As some of the comments are getting at, this is not about Chrome vs. Node (which should behave the same way). It's due to a difference in V8 versions, where Chrome 74 already has the new behavior whereas Node 10 still has the old. Update to Node 11 and you'll see that same behavior there.

In the past, V8 used a combination of QuickSort (for larger arrays) and InsertionSort (for small arrays, up to 10 elements). InsertionSort just so happens to work correctly with the bad comparator function. Use a test array with 11 elements or more, and it will no longer sort correctly in Node 10.

(Versions of V8 since 7.4 now use TimSort for Array.prototype.sort.)

I know that that's not what this question is about, but for the record and/or anyone else reading this in the future: (pre, next) => pre <= next is not a good comparator function! In JavaScript, Array.prototype.sort expects a comparator that returns a number less than zero, equal to zero, or greater than zero, depending on whether the first argument is less than, equal to, or greater than the second. So the proper way to sort strings is something like:

```<code>my_string_array.sort((a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
});
</code>```

When you use such a comparator, you will always get the right result, in all versions of Chrome and Node.

When you use a comparator that uses a single comparison and hence returns a boolean value, then true silently maps to 1 and false maps to 0, but that means it accidentally returns "equal" for a bunch of pairs that are not, in fact, equal, which can lead to quite surprising sorting results, especially when the engine uses an unstable sorting algorithm under the hood.

Body:
I found the sort method shows different behavior between in Chrome environment and in the node environment

const arr = ['l', 'h', 'z', 'b', 's'];
arr.sort((pre, next) => {
    return pre < next;
});
console.log(arr);

the node environment's result is [ 'z', 's', 'l', 'h', 'b' ], it's sorted.

the chrome console environment's result is ['l', 'h', 'z', 'b', 's'], nothing changed.

chrome's result is what I expect, I don't understand why it working in node environment.

chrome version is 74.0.3729.169 X64

node vsrions is v10.12.0.

Body:
V8 developer here.

As some of the comments are getting at, this is not about Chrome vs. Node (which should behave the same way). It's due to a difference in V8 versions, where Chrome 74 already has the new behavior whereas Node 10 still has the old. Update to Node 11 and you'll see that same behavior there.

In the past, V8 used a combination of QuickSort (for larger arrays) and InsertionSort (for small arrays, up to 10 elements). InsertionSort just so happens to work correctly with the bad comparator function. Use a test array with 11 elements or more, and it will no longer sort correctly in Node 10.

(Versions of V8 since 7.4 now use TimSort for Array.prototype.sort.)

I know that that's not what this question is about, but for the record and/or anyone else reading this in the future: (pre, next) => pre <= next is not a good comparator function! In JavaScript, Array.prototype.sort expects a comparator that returns a number less than zero, equal to zero, or greater than zero, depending on whether the first argument is less than, equal to, or greater than the second. So the proper way to sort strings is something like:

my_string_array.sort((a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
});

When you use such a comparator, you will always get the right result, in all versions of Chrome and Node.

When you use a comparator that uses a single comparison and hence returns a boolean value, then true silently maps to 1 and false maps to 0, but that means it accidentally returns "equal" for a bunch of pairs that are not, in fact, equal, which can lead to quite surprising sorting results, especially when the engine uses an unstable sorting algorithm under the hood.


问:
Laravel selectRange blank option
I am creating a "day" select dropdown. With a selectRange I can do this:

```<code>{{ Form::selectRange('day', 1, 31, $day) }}
</code>```

The problem is, when the form loads, if $day is not set it selects 1 by default. Is it possible to use selectRange to give them a "Please Choose" option that has a NULL value?

答:
use placeholder

```<code> {{ Form::selectRange('day', 1, 31, $day,['class' => 'form-control input-lg','id'=>'day','placeholder' => 'Please Choose']) }}
</code>```

Title: Laravel selectRange blank option

Body:
I am creating a "day" select dropdown. With a selectRange I can do this:

{{ Form::selectRange('day', 1, 31, $day) }}

The problem is, when the form loads, if $day is not set it selects 1 by default. Is it possible to use selectRange to give them a "Please Choose" option that has a NULL value?

Body:
use placeholder

 {{ Form::selectRange('day', 1, 31, $day,['class' => 'form-control input-lg','id'=>'day','placeholder' => 'Please Choose']) }}


问:
How to call get or any method of requests library of python by passing a method name to function argument?
I am using requests library of python. I wanted to call requests method GET,POST or any method depend on the arguments received in the function call. I will call requests method inside that function. How can i achieve this?

```<code>import requests

def get_endpoint(method,shop, list_obj):
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    a = requests.method(endpoint_api) # this method should be replaced by method argument of a function get_endpoint
get_endpoint('get', "https://abc/", ['john','joe','1368797932'])
</code>```

I expect it will replace method with get,post whichever passed to function and that url will invoke.
For ex. requests.get(endpoint_api) # get is replaced by method and it will call the url.

答:
You can use python eval method to invoke methods with string. Though I am not sure If it's the recommended way to do that.

```<code>import requests

def get_endpoint(method,shop, list_obj):
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    return eval('requests.' + method)(endpoint_api)

get_endpoint('get', "https://abc/", ['john','joe','1368797932'])
</code>```

Body:
I am using requests library of python. I wanted to call requests method GET,POST or any method depend on the arguments received in the function call. I will call requests method inside that function. How can i achieve this?

import requests

def get_endpoint(method,shop, list_obj):
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    a = requests.method(endpoint_api) # this method should be replaced by method argument of a function get_endpoint
get_endpoint('get', "https://abc/", ['john','joe','1368797932'])

I expect it will replace method with get,post whichever passed to function and that url will invoke.
For ex. requests.get(endpoint_api) # get is replaced by method and it will call the url.

Body:
You can use python eval method to invoke methods with string. Though I am not sure If it's the recommended way to do that.

import requests

def get_endpoint(method,shop, list_obj):
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    return eval('requests.' + method)(endpoint_api)

get_endpoint('get', "https://abc/", ['john','joe','1368797932'])


问:
Lookup Error: unknown encoding from robot framework
I have two list, @{results} and @{platformversions}

```<code>@{results} = [['AAAA', 'BBBB']]
@{platformversions} = [['7.0', '8.0']]
</code>```

I want to append them into a file as shown below.

AAAA BBBB

7.0 8.0

My attempts

```<code>*** Test Cases ***

#Ommitted not useful codes

Write output in file
    Write output in file    @{results}
    #Add new line to separate results
    #Write output in file    ${\n}
    Write output in file    @{platformversions}

*** Keywords ***
Write output in file
    [Arguments]     @{output}
    Append To File     ${EXECDIR}/file.txt     @{output}
</code>```

However, i am receiving this error unknown encoding for BBBB and 8.0.

It seems that i have issues appending the list?

Would appreciate if anyone can take a look at it.

答:
@{results} and @{platformversions} are a list of lists. if you are sure that the data you need will be in the first list elements of @{results} and @{platformversions} respectively then make those as individual lists.

Then run the elements of the lists through a FOR loop and write it in the file.

```<code>*** Test Cases ***
Write output to file
    Write output in file    @{results}
    Go to new line
    Write output in file    @{platformversions}

*** Keywords ***
Write output in file
[Arguments]     @{output}
    FOR  ${value}  IN  @{output}
        Append To File     ${EXECDIR}/file.txt     ${value} \t
    END

Go to new line
    Append To File     ${EXECDIR}/file.txt    \n
</code>```

This will result in the following  output:

```<code>AAAA    BBBB
7.0     8.0
</code>```

Body:
I have two list, @{results} and @{platformversions}

@{results} = [['AAAA', 'BBBB']]
@{platformversions} = [['7.0', '8.0']]

I want to append them into a file as shown below.

AAAA BBBB

7.0 8.0

My attempts

*** Test Cases ***

#Ommitted not useful codes

Write output in file
    Write output in file    @{results}
    #Add new line to separate results
    #Write output in file    ${\n}
    Write output in file    @{platformversions}

*** Keywords ***
Write output in file
    [Arguments]     @{output}
    Append To File     ${EXECDIR}/file.txt     @{output}

However, i am receiving this error unknown encoding for BBBB and 8.0.

It seems that i have issues appending the list?

Would appreciate if anyone can take a look at it.

Body:
@{results} and @{platformversions} are a list of lists. if you are sure that the data you need will be in the first list elements of @{results} and @{platformversions} respectively then make those as individual lists.

Then run the elements of the lists through a FOR loop and write it in the file.

*** Test Cases ***
Write output to file
    Write output in file    @{results}
    Go to new line
    Write output in file    @{platformversions}

*** Keywords ***
Write output in file
[Arguments]     @{output}
    FOR  ${value}  IN  @{output}
        Append To File     ${EXECDIR}/file.txt     ${value} \t
    END

Go to new line
    Append To File     ${EXECDIR}/file.txt    \n

This will result in the following  output:

AAAA    BBBB
7.0     8.0


问:
Trouble moving files in PowerShell using forfiles to a folder whose name has more than one word
I'm new to PowerShell, and am trying to move a few excel spreadsheets into a folder titled "old folder" using the forfiles command. PowerShell says that the files have been moved, but when I check the folder they're not there. They aren't in their original location either.

```<code>forfiles /P C:\Users\NewUser\Desktop /M *.xlsx /D +27/05/2019 /C 'cmd /c move @file C:\Users\NewUser\Desktop\"old folder"\'
</code>```

I tried changing the folder name to a single word "oldfolder" and it worked just fine. What am I doing wrong?

答:
There seems to be a problem with the syntax of your /C parameter. As far as I can tell the argument should be enclosed in double-quotes. And because of the space in the file name that should also be enclosed in double-quotes. Quotes within quotes should be escaped with backslash.
I would suggest this:</p>

```<code>forfiles /P C:\Users\NewUser\Desktop /M *.xlsx /D +27/05/2019 /C "cmd /c move @file \"C:\Users\NewUser\Desktop\old folder\""
</code>```

Body:
I'm new to PowerShell, and am trying to move a few excel spreadsheets into a folder titled "old folder" using the forfiles command. PowerShell says that the files have been moved, but when I check the folder they're not there. They aren't in their original location either.

forfiles /P C:\Users\NewUser\Desktop /M *.xlsx /D +27/05/2019 /C 'cmd /c move @file C:\Users\NewUser\Desktop\"old folder"\'

I tried changing the folder name to a single word "oldfolder" and it worked just fine. What am I doing wrong?

Body:
There seems to be a problem with the syntax of your /C parameter. As far as I can tell the argument should be enclosed in double-quotes. And because of the space in the file name that should also be enclosed in double-quotes. Quotes within quotes should be escaped with backslash.
I would suggest this:

forfiles /P C:\Users\NewUser\Desktop /M *.xlsx /D +27/05/2019 /C "cmd /c move @file \"C:\Users\NewUser\Desktop\old folder\""


问:
Ionic 4 pagination
I have simple provider and it gets data from API url, I need help to paginate this data and load it by IonInfiniteScroll.

Provider

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { LoadingController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class CategoriesService {

  apiUrl = 'https://example.com/api/categories';

  constructor(private http: HttpClient, private loadingCtrl: LoadingController) { }

  getDetails(url) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Accept': 'application/json, text/plain',
        'Content-Type': 'application/json'
      })
    };

    return this.http.get(`${this.apiUrl}/${url}`, httpOptions).pipe(
      map(category => category)
    );
  }
}
```

<p><strong>Module</strong></p>

<pre class="lang-js prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { CategoriesService } from './../../services/categories.service';
import { LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-categories-details',
  templateUrl: './categories-details.page.html',
  styleUrls: ['./categories-details.page.scss'],
})
export class CategoriesDetailsPage implements OnInit {

  categories: Observable<any>;
  loading: any;

  constructor(
    private categoriesService: CategoriesService,
    public loadingController: LoadingController,
  ) {}

  ngOnInit() {
    this.getData();
  }

  async getData(){
    this.loading = await this.loadingController.create({
      message: 'Please wait...',
      spinner: 'crescent',
      duration: 2000
    });

    await this.loading.present();

    this.categoriesService.getCategories().subscribe((res) => {
      this.categories = res;
      this.hideLoading()
    });
  }

  private hideLoading() {
    this.loading.dismiss();
  }

}
</code>```

Note loading: any; current loading just show loading till page loads, it returns all posts at once, it has nothing to do with posts pagination or just loading first 10 of them.

This code currently working just fine, all I need to make sort of pagination and add scroll loading.

View

This code returns each category posts which I need to paginate (posts)

<ion-content padding>
    <ion-grid>
        <ion-row>
          <ion-list *ngIf="category">
            <ion-item *ngFor="let post of category.posts">
              <ion-avatar slot="start">

              </ion-avatar>
                <ion-label class="ion-text-wrap" [routerLink]="['/', 'posts', post.url]">{{post.title}}</ion-label>
            </ion-item>
          </ion-list>
        </ion-row>
      </ion-grid>
</ion-content>
```

Any idea which part should I change and how?

答:
Parameterize your getData() function to take in pageNumber and/or skip parameters, and invoke it in the (ionInfinite) output event of ion-infinite-scroll. Modify the url variable with the pagination parameters to fetch the required data.

Also, when the total data equals the fetched data, disable infiniteScroll.

Title: Ionic 4 pagination

Body:
I have simple provider and it gets data from API url, I need help to paginate this data and load it by IonInfiniteScroll.

Provider

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { LoadingController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class CategoriesService {

  apiUrl = 'https://example.com/api/categories';

  constructor(private http: HttpClient, private loadingCtrl: LoadingController) { }

  getDetails(url) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Accept': 'application/json, text/plain',
        'Content-Type': 'application/json'
      })
    };

    return this.http.get(`${this.apiUrl}/${url}`, httpOptions).pipe(
      map(category => category)
    );
  }
}

Module

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { CategoriesService } from './../../services/categories.service';
import { LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-categories-details',
  templateUrl: './categories-details.page.html',
  styleUrls: ['./categories-details.page.scss'],
})
export class CategoriesDetailsPage implements OnInit {

  categories: Observable<any>;
  loading: any;

  constructor(
    private categoriesService: CategoriesService,
    public loadingController: LoadingController,
  ) {}

  ngOnInit() {
    this.getData();
  }

  async getData(){
    this.loading = await this.loadingController.create({
      message: 'Please wait...',
      spinner: 'crescent',
      duration: 2000
    });

    await this.loading.present();

    this.categoriesService.getCategories().subscribe((res) => {
      this.categories = res;
      this.hideLoading()
    });
  }

  private hideLoading() {
    this.loading.dismiss();
  }

}

Note loading: any; current loading just show loading till page loads, it returns all posts at once, it has nothing to do with posts pagination or just loading first 10 of them.

This code currently working just fine, all I need to make sort of pagination and add scroll loading.

View

This code returns each category posts which I need to paginate (posts)

<ion-content padding>
    <ion-grid>
        <ion-row>
          <ion-list *ngIf="category">
            <ion-item *ngFor="let post of category.posts">
              <ion-avatar slot="start">

              </ion-avatar>
                <ion-label class="ion-text-wrap" [routerLink]="['/', 'posts', post.url]">{{post.title}}</ion-label>
            </ion-item>
          </ion-list>
        </ion-row>
      </ion-grid>
</ion-content>

Any idea which part should I change and how?