答:
One approach would be to execute it given amount of time per period of time.

Create 2000 instances of Action type which will represent DoIOStuff methods. Then try to start 2000 tasks with this action but only you can get it within 1 second (TakeWhile).

```<code>var period = TimeSpan.FromSeconds(1);
var maxAmountOfCalls = 2000;

var methods = Enumerable.Range(0, maxAmountOfCalls)
    .Select(_ => doIOStuff)
    .ToArray();

var watch = new Stopwatch();
watch.Start();

var tasks = methods
    .Select(method => Task.Run(method))
    .TakeWhile(task => watch.Elapsed < period)
    .ToArray();

watch.Stop();

await Task.WhenAll(tasks);
</code>```

This approach will start less than required amount if time period is short.

Title: How to call my method at a particular throughput in C#?

Body:
One approach would be to execute it given amount of time per period of time.

Create 2000 instances of Action type which will represent DoIOStuff methods. Then try to start 2000 tasks with this action but only you can get it within 1 second (TakeWhile).

var period = TimeSpan.FromSeconds(1);
var maxAmountOfCalls = 2000;

var methods = Enumerable.Range(0, maxAmountOfCalls)
    .Select(_ => doIOStuff)
    .ToArray();

var watch = new Stopwatch();
watch.Start();

var tasks = methods
    .Select(method => Task.Run(method))
    .TakeWhile(task => watch.Elapsed < period)
    .ToArray();

watch.Stop();

await Task.WhenAll(tasks);

This approach will start less than required amount if time period is short.


来源: stackexchange

问:
codeigniter 3 URI routing - geting right hand side from given url
I need to simulate routing in Codeigniter 3, so my question is how to get the right-hand side from any URL programmatically?

for example, some routes that I have:

```<code>$route["blog"] = "Main/blog/en";
$route["blog/(:any)"] = "Main/blog/en/$1";
$route["novosti"] = "Main/blog/sr";
$route["novosti/(:any)"] = "Main/blog/sr/$1";
$route["contact"] = "Main/contact/en";
$route["kontakt"] = "Main/contact/sr";
</code>```

Now I need a function that can return right-hand side for a given URL part something like this:

```<code>echo $this->route->item("novosti/petar")
</code>```

should print then Main/blog/sr/$1 or Main/blog/sr/petar

Is there such a function in Codeigniter, because I can't find it in documentation?

UPDATE:
I am looking throughout system/router class and I see that protected function _parse_routes is doing something similar so if there is no function that can give me what I need I will create one based on this one.

答:
You can fetch the required info using the below code.</p>

```<code>$this->router->routes['novosti/(:any)'];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to simulate routing in Codeigniter 3, so my question is how to get the right-hand side from any URL programmatically?

for example, some routes that I have:

$route["blog"] = "Main/blog/en";
$route["blog/(:any)"] = "Main/blog/en/$1";
$route["novosti"] = "Main/blog/sr";
$route["novosti/(:any)"] = "Main/blog/sr/$1";
$route["contact"] = "Main/contact/en";
$route["kontakt"] = "Main/contact/sr";

Now I need a function that can return right-hand side for a given URL part something like this:

echo $this->route->item("novosti/petar")

should print then Main/blog/sr/$1 or Main/blog/sr/petar

Is there such a function in Codeigniter, because I can't find it in documentation?

UPDATE:
I am looking throughout system/router class and I see that protected function _parse_routes is doing something similar so if there is no function that can give me what I need I will create one based on this one.

Body:
You can fetch the required info using the below code.

$this->router->routes['novosti/(:any)'];


问:
How to hide endpoints from OpenAPI documentation with Springdoc
Springdoc automatically generates a API documentation for all handler methods. Even if there are no OpenAPI annotations.

How can I hide endpoints from the API documentation?

答:
If you are working with Swagger Api and you want to hide specific endpoint then use  @ApiOperation(value = "Get Building",hidden=true) on that endpoint...hidden attribute should be true.

```<code>@RestController
@Api(tags="Building")
@RequestMapping(value="/v2/buildings")
public class BuildingsController {

    @ApiOperation(value = "Get Building",hidden=true)
    @GetMapping(value = "/{reference}")
    public Account getBuildings(@PathVariable String reference) {
        ....
    }
</code>```

Body:
If you are working with Swagger Api and you want to hide specific endpoint then use  @ApiOperation(value = "Get Building",hidden=true) on that endpoint...hidden attribute should be true.

@RestController
@Api(tags="Building")
@RequestMapping(value="/v2/buildings")
public class BuildingsController {

    @ApiOperation(value = "Get Building",hidden=true)
    @GetMapping(value = "/{reference}")
    public Account getBuildings(@PathVariable String reference) {
        ....
    }


问:
react countdown timer isn't decrementing well, it is inconsistently changing numbers
it is not countdowning properly, it begins to go crazy when it reach 50 seconds, I think the problem is in my useEffect but I cant point it,

```<code>import React, { useState, useCallback, useEffect, useRef } from 'react'

function App()
{
   const [minute,setMinute]=useState(1)
   const [second,setSecond]=useState(3)
   const[start,setStart]=useState(false)

const IntervalRef=useRef()
useEffect(()=>{
    if(start==true)
    {
      IntervalRef.current=setInterval(()=>{
            if(second!=0)
            {
                setSecond(second-1)
            }
            if(second==0&&minute!=0)
            {
                setSecond(59)
                setMinute(minute-1)
            }
            else
            {
                    clearInterval(IntervalRef.current)
            }
       },1000)
    }
})

    return(
       <div>
           {minute}:{second}
    <button onClick={()=>setStart(!start)}>{start?"pause":"start"}</button>

       </div>
    )
}

export default App
</code>```

it is not countdowning properly, it begins to go crazy when it reach 50 seconds, I think the problem is in my useEffect but I cant point it,

答:
You should clear the interval after each effect runs since the effect runs each render cycle and recreates an interval each time. The effect runs again after each state update. I suspect some clock skew is also to blame and that is why you see the state updates get "out of sync".

```<code>useEffect(() => {
  if (start == true) {
    IntervalRef.current = setInterval(() => {
      if (second != 0) {
        setSecond(second - 1);
      }
      if (second == 0 && minute != 0) {
        setSecond(59);
        setMinute(minute - 1);
      } else {
        clearInterval(IntervalRef.current);
      }
    }, 1000);
  }

  return () => clearInterval(IntervalRef.current); // return an effect cleanup function
});
</code>```

An improved component could use just a seconds state value because computing minutes is trivial.

```<code>displayMinutes = Math.floor(seconds / 60);
displaySeconds = seconds % 60;
</code>```

Implementation

```<code>function App() {
  const [seconds, setSeconds] = useState(63);
  const [start, setStart] = useState(false);

  const IntervalRef = useRef();
  useEffect(() => {
    if (start) {
      const tick = () => setSeconds(t => t - 1);
      IntervalRef.current = setInterval(tick, 1000);
    } else {
      clearInterval(IntervalRef.current)
    }

    return () => clearInterval(IntervalRef.current)
  }, [start]); // <-- start is dependency so effect runs on mount and only when start is updated

  return (
    <div>
      {Math.floor(seconds / 60)}:{seconds % 60}
      <button onClick={() => setStart(start => !start)}>
        {start ? "pause" : "start"}
      </button>
    </div>
  );
}
</code>```

Body:
it is not countdowning properly, it begins to go crazy when it reach 50 seconds, I think the problem is in my useEffect but I cant point it,

import React, { useState, useCallback, useEffect, useRef } from 'react'

function App()
{
   const [minute,setMinute]=useState(1)
   const [second,setSecond]=useState(3)
   const[start,setStart]=useState(false)

const IntervalRef=useRef()
useEffect(()=>{
    if(start==true)
    {
      IntervalRef.current=setInterval(()=>{
            if(second!=0)
            {
                setSecond(second-1)
            }
            if(second==0&&minute!=0)
            {
                setSecond(59)
                setMinute(minute-1)
            }
            else
            {
                    clearInterval(IntervalRef.current)
            }
       },1000)
    }
})

    return(

           {minute}:{second}
    <button onClick={()=>setStart(!start)}>{start?"pause":"start"}</button>

    )
}

export default App

it is not countdowning properly, it begins to go crazy when it reach 50 seconds, I think the problem is in my useEffect but I cant point it,

Body:
You should clear the interval after each effect runs since the effect runs each render cycle and recreates an interval each time. The effect runs again after each state update. I suspect some clock skew is also to blame and that is why you see the state updates get "out of sync".

useEffect(() => {
  if (start == true) {
    IntervalRef.current = setInterval(() => {
      if (second != 0) {
        setSecond(second - 1);
      }
      if (second == 0 && minute != 0) {
        setSecond(59);
        setMinute(minute - 1);
      } else {
        clearInterval(IntervalRef.current);
      }
    }, 1000);
  }

  return () => clearInterval(IntervalRef.current); // return an effect cleanup function
});

An improved component could use just a seconds state value because computing minutes is trivial.

displayMinutes = Math.floor(seconds / 60);
displaySeconds = seconds % 60;

Implementation

function App() {
  const [seconds, setSeconds] = useState(63);
  const [start, setStart] = useState(false);

  const IntervalRef = useRef();
  useEffect(() => {
    if (start) {
      const tick = () => setSeconds(t => t - 1);
      IntervalRef.current = setInterval(tick, 1000);
    } else {
      clearInterval(IntervalRef.current)
    }

    return () => clearInterval(IntervalRef.current)
  }, [start]); // <-- start is dependency so effect runs on mount and only when start is updated

  return (
    <div>
      {Math.floor(seconds / 60)}:{seconds % 60}
      <button onClick={() => setStart(start => !start)}>
        {start ? "pause" : "start"}
      </button>
    </div>
  );
}


问:
Multi Dimensional PHP Arrays into Javascript Arrays
I'm able to print the following item name values using the following in PHP.

I'm stuck trying to take a PHP array, and use it in JavaScript.

```<code>foreach($orderArray[0]->items as $data){
    echo $data->name; echo "<br>";
    echo $data->productId; echo "<br>";
}
</code>```

How would I take this array, and make this an array in JavaScript and print the values of name and productId for each item ?

I'm new to JavaScript and know I can convert the array as below, but not sure how to get the values into a JavaScript's Multidimensional Associative array, where I can print the values in JavaScript.

```<code>var array1 = '<?php echo json_encode($orderArray); ?>';
</code>```

答:
Your code is all correct and here after you can access elements in an array similar to that of the PHP array as

```<code><?php
$data = [1 => [1,2,3],2,3,4,5,6];
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<p>
<script>
var a = <?php echo json_encode($data);?>;
document.write(a[1]);
</script>
</p>
</body>
</html>
</code>```

Output

```<code>1,2,3
</code>```

And you can also access the elements in the for loop similar to that of the PHP array.

Body:
I'm able to print the following item name values using the following in PHP.

I'm stuck trying to take a PHP array, and use it in JavaScript.

foreach($orderArray[0]->items as $data){
    echo $data->name; echo "
";
    echo $data->productId; echo "
";
}

How would I take this array, and make this an array in JavaScript and print the values of name and productId for each item ?

I'm new to JavaScript and know I can convert the array as below, but not sure how to get the values into a JavaScript's Multidimensional Associative array, where I can print the values in JavaScript.

var array1 = '<?php echo json_encode($orderArray); ?>';

Body:
Your code is all correct and here after you can access elements in an array similar to that of the PHP array as

<?php
$data = [1 => [1,2,3],2,3,4,5,6];
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<p>
<script>
var a = <?php echo json_encode($data);?>;
document.write(a[1]);
</script>
</p>
</body>
</html>

Output

1,2,3

And you can also access the elements in the for loop similar to that of the PHP array.


问:
Is there a better way to check if a number is range of two numbers
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

```<code>def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000
</code>```

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

答:
you should replace:

```<code>if number in range(0,5499):
</code>```

with

```<code>if 0 <= number < 5499 :
</code>```

which is much faster and less memory intensive.

Body:
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

Body:
you should replace:

if number in range(0,5499):

with

if 0 <= number < 5499 :

which is much faster and less memory intensive.


问:
How to store access tokens in Firebase back-end?
My React app uses Firebase Authentication and the Real-Time Database. I now need to access 3rd party services using OAuth 2.0. To do this securely, I am using the OAuth 2.0 Authorization Code Flow with Firebase Functions as my back-end:

React app gets an Authorization Code from the 3rd party.

Authorization code is passed to a Firebase function to get an access token.

But this is where I am stuck. How do I save the access token in the backend so that the React app can access the 3rd party resources? I don't want to store the access token in the React app because that's not secure.

How do I maintain a session in the back-end using Firebase Functions?

Should the session be tied to the React app instance or the Firebase user? The former approach would require a session cleanup. The latter has the advantage that new access tokens can be obtained using a refresh token. This way the user never has to login to the 3rd party again!

答:
After trying bunch of different approaches, I ended up storing the access token & the refresh token in the back-end, both tied to the firebase user. The tokens are only accessible through firebase functions. This approach has the following advantages:

Secure

I don't have to worry about sessions and session cleanup.

I can refresh the access token whenever I want using the refresh token.


问:
Determining binary/text file type in Java?
Namely, how would you tell an archive (jar/rar/etc.) file from a textual (xml/txt, encoding-independent) one?</p>

答:
If the file consists of the bytes 0x09 (tab), 0x0A (line feed), 0x0C (form feed), 0x0D (carriage return), or 0x20 through 0x7E, then it's probably ASCII text.

If the file contains any other ASCII control character, 0x00 through 0x1F excluding the three above, then it's probably binary data.

UTF-8 text follows a very specific pattern for any bytes with the high order bit, but fixed-length encodings like ISO-8859-1 do not. UTF-16 can frequently contain the null byte (0x00), but only in every other position.

You'd need a weaker heuristic for anything else.

OwnerDisplayName: gsmd

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
AWS S3 policy to allow access to buckets ending with particular name
Is it possible to write an AWS S3 policy such that

can read all objects in bucket which names ending in "archive" (the bucket name ending in archive, no constraint on object names)

can read-write all objects in buckets ending in "output"

Can that be done?

I can't find "conditions" that would allow me to do that...

Thanks

PS:
1) I just edited the question because there was ambiguity as whether it was the bucket or the object name ending in "..."
2) I have since gathered that I can't filter the names of the buckets that can be listed
3) The comment from bruno-reis makes it clear that it would be a bad idea anyway

答:
No, this is not possible.

You are asking for a policy that applies to multiple buckets. Therefore, this would need to be an IAM Policy because a Bucket Policy only applies to a specific bucket.

While IAM policies allow wildcards, they are pretty limited in their capability. For example, this policy would appear to work, and does indeed grant access to a bucket ending with -output:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::*-output/*"
        }
    ]
}
</code>```

So, this command will succeed:

```<code>aws s3 cp foo-output/bar.txt .
</code>```

However, it also allows this command:

```<code>aws s3 cp foo/results-output/bar.txt .
</code>```

This is because the wildcards in the policy do not differentiate between the part of the ARN that refers to the bucket name and the path/object name.

So, it is possible that they can access a bucket that does not end in -output. Thus, it is an unsafe policy.

Body:
No, this is not possible.

You are asking for a policy that applies to multiple buckets. Therefore, this would need to be an IAM Policy because a Bucket Policy only applies to a specific bucket.

While IAM policies allow wildcards, they are pretty limited in their capability. For example, this policy would appear to work, and does indeed grant access to a bucket ending with -output:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::*-output/*"
        }
    ]
}

So, this command will succeed:

aws s3 cp foo-output/bar.txt .

However, it also allows this command:

aws s3 cp foo/results-output/bar.txt .

This is because the wildcards in the policy do not differentiate between the part of the ARN that refers to the bucket name and the path/object name.

So, it is possible that they can access a bucket that does not end in -output. Thus, it is an unsafe policy.


问:
Is there any way to make this code shorter, and more efficient?
I was learning javascript, and trying different projects/coding challenges. After writing this code I realised that it is 43 lines (this is for a basic image slider), and it could not be the most efficient method for doing this. Is there any way to shorten my code, or make it more efficient?
This script says when you press right, it goes to the next image, and when you press left, it goes to the previous image

// Try edit message
const data = [
  {
    image:"https://image.shutterstock.com/image-photo/bright-spring-view-cameo-island-260nw-1048185397.jpg",
  },
  {
    image:"https://image.shutterstock.com/image-photo/mountains-during-sunset-beautiful-natural-260nw-407021107.jpg",
  },
]

let img = document.querySelector("img")
let left = document.querySelector('#left')
let right = document.querySelector('#right')
let origin = 0
img.src = data[origin].image

function incr(number){
  if (number == 'left') {
    if (origin - 1 >= 0){
      origin += -1
    }else{
      origin = data.length - 1
    }
  }else if (number == 'right'){
    if (origin + 1 <= data.length - 1){
      origin += 1
    }else{
      origin = 0
    }
    }
  return origin;
  }

function moveleft(){
  let value = incr('left')
  img.src = data[value].image
}

function moveright(){
  let value = incr('right')
  img.src = data[value].image
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="https://playcode.io/static/img/logo.png" width = 1280px height = 720px>
  <button onclick = "moveleft()" id = 'left'>left</button>
  <button onclick = "moveright()" id = 'right'>right</button>
</div></code>```

All help apreciated, thanks.

答:
You could do something like this:

```<code>function incr(offset) {
  // either +1 or +(-1)
  const incremented = origin + offset;
  // Take the smallest value out of the 2, effectively constrains to <= len - 1
  const constrainedUpper = Math.min(data.length - 1, incremented);
  // Take the largest value out of the 2, effectively constrains to >= 0
  const constrainedLower = Math.max(0, constrainedUpper);
  origin = constrainedLower;
}

function moveleft(){
  incr(-1)
  img.src = data[origin].image;
}

function moveright(){
  incr(1)
  img.src = data[origin].image
}
</code>```

Removing the 'left' and 'right' since they are really just indicators for how much you want to move. Then, use the math functions to constrain the result to 0 and data.length - 1.

Body:
I was learning javascript, and trying different projects/coding challenges. After writing this code I realised that it is 43 lines (this is for a basic image slider), and it could not be the most efficient method for doing this. Is there any way to shorten my code, or make it more efficient?
This script says when you press right, it goes to the next image, and when you press left, it goes to the previous image

// Try edit message
const data = [
  {
    image:"https://image.shutterstock.com/image-photo/bright-spring-view-cameo-island-260nw-1048185397.jpg",
  },
  {
    image:"https://image.shutterstock.com/image-photo/mountains-during-sunset-beautiful-natural-260nw-407021107.jpg",
  },
]

let img = document.querySelector("img")
let left = document.querySelector('#left')
let right = document.querySelector('#right')
let origin = 0
img.src = data[origin].image

function incr(number){
  if (number == 'left') {
    if (origin - 1 >= 0){
      origin += -1
    }else{
      origin = data.length - 1
    }
  }else if (number == 'right'){
    if (origin + 1 <= data.length - 1){
      origin += 1
    }else{
      origin = 0
    }
    }
  return origin;
  }

function moveleft(){
  let value = incr('left')
  img.src = data[value].image
}

function moveright(){
  let value = incr('right')
  img.src = data[value].image
}

  <button onclick = "moveleft()" id = 'left'>left</button>
  <button onclick = "moveright()" id = 'right'>right</button>

All help apreciated, thanks.

Body:
You could do something like this:

function incr(offset) {
  // either +1 or +(-1)
  const incremented = origin + offset;
  // Take the smallest value out of the 2, effectively constrains to <= len - 1
  const constrainedUpper = Math.min(data.length - 1, incremented);
  // Take the largest value out of the 2, effectively constrains to >= 0
  const constrainedLower = Math.max(0, constrainedUpper);
  origin = constrainedLower;
}

function moveleft(){
  incr(-1)
  img.src = data[origin].image;
}

function moveright(){
  incr(1)
  img.src = data[origin].image
}

Removing the 'left' and 'right' since they are really just indicators for how much you want to move. Then, use the math functions to constrain the result to 0 and data.length - 1.


问:
Python CSV to Array
Need some help pls. I have a csv file in the following format.
input.csv

```<code>Project1,folder1/file1,data
Project1,folder1/file2,data
Project1,folder1/file3,data
Project1,folder1/file4,data
Project1,folder2/file11,data
Project1,folder2/file42a,data
Project1,folder2/file42b,data
Project1,folder2/file42c,data
Project1,folder2/file42d,data
Project1,folder3/filec,data
Project1,folder3/fileb,data
Project1,folder3/filea,data
</code>```

Basically, ignore all columns except column #2. This column is like a directory tree, in the format <foldername> forwardslash <filename>. There is no header-row.

I wish Python ver 3x, to read this file and make this into an array in the following format. The input csv file is large and hence need an efficient way to this pls.

```<code>print(out_array)

'folder1/file1', 'folder1/file2', 'folder1/file3', 'folder1/file4'
'folder2/file11', 'folder2/file42a', 'folder2/file42b', 'folder2/file42c', 'folder2/file42d'
'folder3/filec', 'folder3/fileb', 'folder3/filea'
</code>```

Each folder is output on a new row. The input csv file, will not have the folder names jumbled up. Hence, all rows for folder1 will be together, and not mixed with others.

答:
To a pure python implementation, you should use the package csv.

Suppose the file you would like to read is in current directory with the main.py.

data.csv

```<code>Project1,folder1/file1,data
Project1,folder1/file2,data
Project1,folder1/file3,data
Project1,folder1/file4,data
Project1,folder2/file11,data
Project1,folder2/file42a,data
Project1,folder2/file42b,data
Project1,folder2/file42c,data
Project1,folder2/file42d,data
Project1,folder3/filec,data
Project1,folder3/fileb,data
Project1,folder3/filea,data
</code>```

main.py

```<code>import csv
a = []
b = []
with open('data.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    for row in reader:
        a.append(row[1])

    for item in a:
        c = []
        for item2 in a:
            inicio = item2.split('/')[0]
            if len(c) == 0 and inicio in item:
                c.append(item2)
            elif inicio in item:
                c.append(item2)
        if c not in b:
            b.append(c)

print(b)
</code>```

output:

```<code>[['folder1/file1', 'folder1/file2', 'folder1/file3', 'folder1/file4'], ['folder2/file11', 'folder2/file42a', 'folder2/file42b', 'folder2/file42c', 'folder2/file42d'], ['folder3/filec', 'folder3/fileb', 'folder3/filea']]
</code>```

Hope it helps

Title: Python CSV to Array

Body:
Need some help pls. I have a csv file in the following format.
input.csv

Project1,folder1/file1,data
Project1,folder1/file2,data
Project1,folder1/file3,data
Project1,folder1/file4,data
Project1,folder2/file11,data
Project1,folder2/file42a,data
Project1,folder2/file42b,data
Project1,folder2/file42c,data
Project1,folder2/file42d,data
Project1,folder3/filec,data
Project1,folder3/fileb,data
Project1,folder3/filea,data

Basically, ignore all columns except column #2. This column is like a directory tree, in the format <foldername> forwardslash <filename>. There is no header-row.

I wish Python ver 3x, to read this file and make this into an array in the following format. The input csv file is large and hence need an efficient way to this pls.

print(out_array)

'folder1/file1', 'folder1/file2', 'folder1/file3', 'folder1/file4'
'folder2/file11', 'folder2/file42a', 'folder2/file42b', 'folder2/file42c', 'folder2/file42d'
'folder3/filec', 'folder3/fileb', 'folder3/filea'

Each folder is output on a new row. The input csv file, will not have the folder names jumbled up. Hence, all rows for folder1 will be together, and not mixed with others.

Body:
To a pure python implementation, you should use the package csv.

Suppose the file you would like to read is in current directory with the main.py.

data.csv

Project1,folder1/file1,data
Project1,folder1/file2,data
Project1,folder1/file3,data
Project1,folder1/file4,data
Project1,folder2/file11,data
Project1,folder2/file42a,data
Project1,folder2/file42b,data
Project1,folder2/file42c,data
Project1,folder2/file42d,data
Project1,folder3/filec,data
Project1,folder3/fileb,data
Project1,folder3/filea,data

main.py

import csv
a = []
b = []
with open('data.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    for row in reader:
        a.append(row[1])

    for item in a:
        c = []
        for item2 in a:
            inicio = item2.split('/')[0]
            if len(c) == 0 and inicio in item:
                c.append(item2)
            elif inicio in item:
                c.append(item2)
        if c not in b:
            b.append(c)

print(b)

output:

[['folder1/file1', 'folder1/file2', 'folder1/file3', 'folder1/file4'], ['folder2/file11', 'folder2/file42a', 'folder2/file42b', 'folder2/file42c', 'folder2/file42d'], ['folder3/filec', 'folder3/fileb', 'folder3/filea']]

Hope it helps


问:
My htaccess is not having effect when i serve to a another port on XAMPP
I am having an issue please. I have a project in

C:\xampp\htdocs\woski.

The htacess works when i access it on the browser via

localhost/woski

but the project needs its separate port to function properly.

I run command below in terminal

php -S localhost:3122

I then access the project on the browser via

localhost:3122

The PROBLEM is that the htaccess here doesn't have effect on this separate port 3122.

Everything seems to be working fine except the .htaccess having effect on the project when ran on this port.

How can I solve this issue please?

答:
.htaccess is an Apache configuration file.  The PHP built-in web server is not a full fledged Apache web server.

To use advanced features that Apache provides, you have to install Apache, install PHP, add PHP modules into Apache, then use .htaccess.


问:
Need help scaling an image inside a viewport
I have a Django site that displays an image and I need to zoom in and zoom out using a button while keeping the viewport relatively the same size and use scroll bars to move the image when it is zoomed in. I am not a CSS nor javascript guy, so this attempt is based on a lot of google help.

$(document).ready(function() {
  console.log("Zoom START");
  $('#zoom-in').click(function() {
    updateZoom(0.1);
    console.log("Zoomed in");
  });

  $('#zoom-out').click(function() {
    updateZoom(-0.1);
    console.log("Zoomed out");
  });

  zoomLevel = 1;

  var updateZoom = function(zoom) {
    zoomLevel += zoom;
    $('#imageblock').css({
      zoom: zoomLevel,
      '-moz-transform': 'scale(' + zoomLevel + ')',
      /* Firefox */
      'transform': 'scale(' + zoomLevel + ')',
      //'-ms-transform': 'scale(' + zoomLevel + ')', /* IE 9 */
      '-webkit-transform': 'scale(' + zoomLevel + ')',
      /* Safari and Chrome */
      //'-o-transform': 'scale(' + zoomLevel + ')', /* Opera */

    });
    console.log("updated imageblock css");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#imageblock {
  max-height: 600px;
  max-width: 800px;
  transform-origin: top left;
  overflow: hidden;
}

#imageblock img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}</code>```

Image:

    Click to tag people, Ctrl-click to tag animals
    <button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>

    Rotate 90 degrees

```

The image zooms, but also grows to fill the page without any scrollbars, and does not stay within a viewport (image block). Thanks for any assistance/direction you can give me!

Mark

答:
You might want to use an approach like this with a couple bounding elements to control the clipping and scrolling. See below:

$('input').on('change', function() {
  $('img').css('transform', `scale(${$(this).val()})`);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: scroll;
  display: block;
}

img {
  transform-origin: 0 0;
}</code>```

<input type="number" step="0.1" value="1" min="0" />

```

Body:
I have a Django site that displays an image and I need to zoom in and zoom out using a button while keeping the viewport relatively the same size and use scroll bars to move the image when it is zoomed in. I am not a CSS nor javascript guy, so this attempt is based on a lot of google help.

$(document).ready(function() {
  console.log("Zoom START");
  $('#zoom-in').click(function() {
    updateZoom(0.1);
    console.log("Zoomed in");
  });

  $('#zoom-out').click(function() {
    updateZoom(-0.1);
    console.log("Zoomed out");
  });

  zoomLevel = 1;

  var updateZoom = function(zoom) {
    zoomLevel += zoom;
    $('#imageblock').css({
      zoom: zoomLevel,
      '-moz-transform': 'scale(' + zoomLevel + ')',
      /* Firefox */
      'transform': 'scale(' + zoomLevel + ')',
      //'-ms-transform': 'scale(' + zoomLevel + ')', /* IE 9 */
      '-webkit-transform': 'scale(' + zoomLevel + ')',
      /* Safari and Chrome */
      //'-o-transform': 'scale(' + zoomLevel + ')', /* Opera */

    });
    console.log("updated imageblock css");
  }
});

#imageblock {
  max-height: 600px;
  max-width: 800px;
  transform-origin: top left;
  overflow: hidden;
}

#imageblock img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

Image:

    Click to tag people, Ctrl-click to tag animals
    <button type="button" id="zoom-in">zoom in</button> <button type="button" id="zoom-out">zoom out</button>

    Rotate 90 degrees

The image zooms, but also grows to fill the page without any scrollbars, and does not stay within a viewport (image block). Thanks for any assistance/direction you can give me!

Mark

Body:
You might want to use an approach like this with a couple bounding elements to control the clipping and scrolling. See below:

$('input').on('change', function() {
  $('img').css('transform', `scale(${$(this).val()})`);
});

div {
  width: 300px;
  height: 300px;
  border: 1px solid #000000;
  overflow: scroll;
  display: block;
}

img {
  transform-origin: 0 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="number" step="0.1" value="1" min="0" />

<div>
  <img src="http://placekitten.com/g/250/250" />
</div>


问:
How can I use github api to decide the dependencies between two commit?
I know that GitHub offer an api to compare two commit like https://developer.github.com/v3/repos/commits/#compare-two-commits. However, I wonder if I can use api on GitHub to decide the relationship between two commits. See the following commit graph:

```<code>A ---> B ---> C ---> D
└--->E---------------┘
</code>```

From the above, commit A is the predecessor of commit B & commit E, while commit B is not predecessor of commit E.
Considering my situation, judge whether commit A is predecessor of commit B is enough. Thanks a lot!

答: One of my instructors suggests that, we can download the commit message to the sql database, then query the relationship. since github api message contains commit's previous_commit, we can use this to construct the relationship. </p>

Body:
I know that GitHub offer an api to compare two commit like https://developer.github.com/v3/repos/commits/#compare-two-commits. However, I wonder if I can use api on GitHub to decide the relationship between two commits. See the following commit graph:

A ---> B ---> C ---> D
└--->E---------------┘

From the above, commit A is the predecessor of commit B & commit E, while commit B is not predecessor of commit E.
Considering my situation, judge whether commit A is predecessor of commit B is enough. Thanks a lot!


问:
can we write mongodb crud queries and aggregate query together?
In MongoDB can we execute below written query?

```<code>db.dbaname.find(userName:"abc").aggregate([])
</code>```

else is there any other way we can execute CRUD and aggregate query together.

答:
Short answer - No you can't do this : .find(userName:"abc").aggregate([])

aggregation-pipeline is heavily used for reads which is mostly similar to .find() but capable of executing complex queries with help of it's multiple stages & many aggregation-operators. there are only two stages in aggregation $out & $merge that can perform writes to database - these stages are not that much used compared to other stages & needs to be used only when needed & as they need to be last stages in aggregation pipeline, then all the previous stages are to be tested very well. So when it comes to CRUD eliminating CUD you'll benefit over R - Reads.

Same .find(userName:"abc") can be written as :

```<code>.aggregate( [ { $match : { userName:"abc"} } ] ) // Using `$match` stage
</code>```

Body:
In MongoDB can we execute below written query?

db.dbaname.find(userName:"abc").aggregate([])

else is there any other way we can execute CRUD and aggregate query together.

Body:
Short answer - No you can't do this : .find(userName:"abc").aggregate([])

aggregation-pipeline is heavily used for reads which is mostly similar to .find() but capable of executing complex queries with help of it's multiple stages & many aggregation-operators. there are only two stages in aggregation $out & $merge that can perform writes to database - these stages are not that much used compared to other stages & needs to be used only when needed & as they need to be last stages in aggregation pipeline, then all the previous stages are to be tested very well. So when it comes to CRUD eliminating CUD you'll benefit over R - Reads.

Same .find(userName:"abc") can be written as :

.aggregate( [ { $match : { userName:"abc"} } ] ) // Using `$match` stage


问:
Check if there are higher values in 2 columns (C&D) on other sheet based on cell value in column B & autopopulate result
Link to Google Sheet Sample

In column E on sheet 'Calc', I want to check if there's a person in sheet 'Data' who has the same A value, but a higher value on B and C. Eventually I want to Return 'No' if not, return 'yes' if yes. If there's a person with the same A value who has a higher value on B but not on C (or vice versa) return 'maybe' with the name of the person(s). Autopopulate E with the returned value.

The values in columns B, C and D in 'Calc' are dynamic and will change based on other calculations. The B, C and D values in 'Data' are static. The length of both columns can differ.

Some examples:

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C75. No-one else has A89 and higher values on both B or C.

Return 'Yes'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B60, C55. No-one else has A89 and higher values on both B or C.

Return 'No'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. No-one else has A89 and higher values on both B or C.

Return 'Maybe: Person A'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. Person B in sheet 'Data' has the values of A89, B55, C71. Person A has the highest value on B compared to the people in sheet 'Data' with A89 but a C lower than that of Name 1 in sheet 'Calc'. Person B has the highest value on C compared to the people in sheet 'Data' with A89 but a B lower than the of Name 1 in sheet 'Calc'.
Return 'Maybe: Person A, Person B'.

I've tried to make a start by just getting the highest values in sheet 'Calc' by combining =ARRAYFORMULA with MAX, but I get either a 'different number' array error or everything is just compared to B3.

Error:

```<code>=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))
</code>```

Only calculated with B3:

```<code>=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))
</code>```

Edit: I've removed the open-ended ranges which at least removed the error I got, but it still doesn't return the desired numbers (it returns either zero or the highest numbers belonging to the first entry, B3). I've updated the sheet accordingly.

```<code>=ARRAYFORMULA(IF(ISBLANK($A3:$A999);;$B$3:$B$999&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$C3:$C999)&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$D3:$D999)))
</code>```

答:
I've not found a way to autopopulate it yet, but this solution works for me because I can just copy it to a lot of cells by combining an IF-statement with a ISBLANK() formula.

Basically I've used this, wrapped in a couple of if-statements, changed the returned data according to my needs, and built the code up from there. It returns the desired cell-value from the person with the highest B-value and who's A-value corresponds with the one on the CALC sheet.

```<code>INDEX(
    Data!$C:$C
    ;
    MATCH(
        MAXIFS(
            Data!$C$3:$C$100
            ;
            Data!$B$3:$B$100
            ;
            $B3
        )
        ;
        Data!$C:$C
        ;
        0
    )
)
</code>```

The code in column M in the sample-sheet is the code that I've started using. It's not pretty (at all) and could probably be a lot more efficient, but it works and this already took a lot of googling, tries and patience, so I'm a bit at the limit of my google-formula knowledge, haha.

This is the formula I've implemented in this sheet for conditional formatting, should someone need something like it. It picks the maximum value of a column based on a criteria in another:

```<code>=$E3=MAXIFS($E$3:$E$100;$M$3:$M$100;"Yes")
</code>```

Body:
Link to Google Sheet Sample

In column E on sheet 'Calc', I want to check if there's a person in sheet 'Data' who has the same A value, but a higher value on B and C. Eventually I want to Return 'No' if not, return 'yes' if yes. If there's a person with the same A value who has a higher value on B but not on C (or vice versa) return 'maybe' with the name of the person(s). Autopopulate E with the returned value.

The values in columns B, C and D in 'Calc' are dynamic and will change based on other calculations. The B, C and D values in 'Data' are static. The length of both columns can differ.

Some examples:

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C75. No-one else has A89 and higher values on both B or C.

Return 'Yes'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B60, C55. No-one else has A89 and higher values on both B or C.

Return 'No'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. No-one else has A89 and higher values on both B or C.

Return 'Maybe: Person A'.

Name 1 in sheet 'Calc' has the values of A89, B70, C70.

Person A in sheet 'Data' has the values of A89, B71, C55. Person B in sheet 'Data' has the values of A89, B55, C71. Person A has the highest value on B compared to the people in sheet 'Data' with A89 but a C lower than that of Name 1 in sheet 'Calc'. Person B has the highest value on C compared to the people in sheet 'Data' with A89 but a B lower than the of Name 1 in sheet 'Calc'.
Return 'Maybe: Person A, Person B'.

I've tried to make a start by just getting the highest values in sheet 'Calc' by combining =ARRAYFORMULA with MAX, but I get either a 'different number' array error or everything is just compared to B3.

Error:

=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))

Only calculated with B3:

=ARRAYFORMULA(IF(ISBLANK($A3:$A);;$B3&":"&MAX((Data!$B3:$B=$B3)*Data!$C3:$C)&":"&MAX((Data!$B3:$B=$B3)*Data!$D3:$D)))

Edit: I've removed the open-ended ranges which at least removed the error I got, but it still doesn't return the desired numbers (it returns either zero or the highest numbers belonging to the first entry, B3). I've updated the sheet accordingly.

=ARRAYFORMULA(IF(ISBLANK($A3:$A999);;$B$3:$B$999&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$C3:$C999)&":"&MAX((Data!$B3:$B999=$B$3:$B$999)*Data!$D3:$D999)))

Body:
I've not found a way to autopopulate it yet, but this solution works for me because I can just copy it to a lot of cells by combining an IF-statement with a ISBLANK() formula.

Basically I've used this, wrapped in a couple of if-statements, changed the returned data according to my needs, and built the code up from there. It returns the desired cell-value from the person with the highest B-value and who's A-value corresponds with the one on the CALC sheet.

INDEX(
    Data!$C:$C
    ;
    MATCH(
        MAXIFS(
            Data!$C$3:$C$100
            ;
            Data!$B$3:$B$100
            ;
            $B3
        )
        ;
        Data!$C:$C
        ;
        0
    )
)

The code in column M in the sample-sheet is the code that I've started using. It's not pretty (at all) and could probably be a lot more efficient, but it works and this already took a lot of googling, tries and patience, so I'm a bit at the limit of my google-formula knowledge, haha.

This is the formula I've implemented in this sheet for conditional formatting, should someone need something like it. It picks the maximum value of a column based on a criteria in another:

=$E3=MAXIFS($E$3:$E$100;$M$3:$M$100;"Yes")


问:
How do you write or replace a url in a function using onClick?
I'm new to javascript and I'm having a particularly difficult time figuring out how write new urls into an existing function using onClick.

Here is some more info:

I want to have something like this

```<code>   <script type="text/javascript">

    function addurl(){
    "server": [
                 {
                    "position": "center",
                    "url": "New_Url"
                 }
              ]
                     }
    </script>

    <div id="urlbutton"></div>
    <input type="button" onclick="????" value="url123">
</code>```

Basically I want to replace the "url" when clicking different buttons/links. I've spent hours and hours today trying to figure this out and now I'm basically all turned around not knowing what to do.

Any type of help will be greatly appreciated!

答:
Try this </p>

```<code> <script type="text/javascript">

    function addurl(newUrl){
    "server": [
                 {
                    "position": "center",
                    "url": newUrl
                 }
              ]
                     }
    </script>

 <input type="button" onclick="addUrl();" value="url123">
</code>```

Body:
I'm new to javascript and I'm having a particularly difficult time figuring out how write new urls into an existing function using onClick.

Here is some more info:

I want to have something like this

    <input type="button" onclick="????" value="url123">

Basically I want to replace the "url" when clicking different buttons/links. I've spent hours and hours today trying to figure this out and now I'm basically all turned around not knowing what to do.

Any type of help will be greatly appreciated!

Body:
Try this

 <script type="text/javascript">

    function addurl(newUrl){
    "server": [
                 {
                    "position": "center",
                    "url": newUrl
                 }
              ]
                     }
    </script>

 <input type="button" onclick="addUrl();" value="url123">


问:
How come address value stored in an array is same as its own address, it should be pointing to some different address (&arr[0])?
```<code>#include<iostream>
using namespace std;
int main()
{
int arr[3]{0,1,2};
cout<<"The value of arr "<<arr<<'\n';
cout<<"The address of &arr "<<&arr<<'\n';
cout<<"The address of &arr[0] "<<&arr[0]<<'\n';
cout<<"The value in arr[0] "<<arr[0]<<'\n';
}

OUTPUT

The value of arr 0x7ffd1a658e74
The address of &arr 0x7ffd1a658e74
The address of &arr[0] 0x7ffd1a658e74
The value in arr[0] 0
</code>```

Here address value in array arr is same as &arr, since array is a pointer pointing to its first element so value arr should be equal equal to &arr[0] which is found equal to &arr. So how come arr can have two values: address value of &arr[0] and value at arr[0], since arr = &arr[0] = &arr

答:
Let's break this down:

arr is evaluated as a pointer to its first element. So it returns the address of the first element of the array.

&arr is the 'address of the array', which is evaluated to the address of its first element. I think you were stuck up on this one, since arr itself is evaluated as a pointer to the first element, and thus it should be the 'address of the address of the first element'. But in this case, the array is not first evaluated to a pointer to the first element, it just returns the address of it as-is.

&arr[0] is accessing the first element of arr, and then retrieving the address of that.

Thus, all three of these will return the address of the first element.

Edit: One thing that should be noted is the type mismatch between &arr and &arr[0]. The former will be refer to an array type, while the latter will refer to the element type. Doing arithmetic operations with them will lead to wildly different results.

Body:
#include<iostream>
using namespace std;
int main()
{
int arr[3]{0,1,2};
cout<<"The value of arr "<<arr<<'\n';
cout<<"The address of &arr "<<&arr<<'\n';
cout<<"The address of &arr[0] "<<&arr[0]<<'\n';
cout<<"The value in arr[0] "<<arr[0]<<'\n';
}

OUTPUT

The value of arr 0x7ffd1a658e74
The address of &arr 0x7ffd1a658e74
The address of &arr[0] 0x7ffd1a658e74
The value in arr[0] 0

Here address value in array arr is same as &arr, since array is a pointer pointing to its first element so value arr should be equal equal to &arr[0] which is found equal to &arr. So how come arr can have two values: address value of &arr[0] and value at arr[0], since arr = &arr[0] = &arr


问:
Best way to group filename based on filename in Bash?
I have a folder with the following files:

```<code>DA-001-car.jpg
DA-001-dog.jpg
DA-001-coffee.jpg
DA-002-house.jpg
DA-003-coffee.jpg
DA-003-cat.jpg
...
</code>```

I want to generate this (CSV) output:

```<code>SKU, IMAGE
DA-001, "DA-001-car.jpg, DA-001-dog.jpg, DA-001-coffee.jpg"
DA-002, "DA-001-house.jpg"
DA-003, "DA-001-coffee.jpg, DA-001-cat.jpg"
</code>```

I tried to program this in Bash:

```<code>#!/bin/bash
echo "SKU, FILE" >> tmp.csv
for file in /home/calvin/test/*.jpg
do
    SKU_NAME="${file##*/}"
    echo ${SKU_NAME:0:6}, \"inner for-loop?, ?, ?\" >> tmp.csv
done
uniq tmp.csv output.csv
</code>```

As you can see I'm a noob as for programming :)
Please help me out, thanks in advance!

答:
As result of all the replies and advises I'm using this code to achieve the desired output:

```<code>#!/bin/bash

echo "SKU, IMAGES" >> output.csv

ls *.jpg | cut -f1,2 -d- | sort -u | while read SKU
do
    echo $SKU, \"$(echo "$SKU"* | sed 's/ /, /g')\" >> output.csv
done
</code>```

Thanks all!

Body:
I have a folder with the following files:

DA-001-car.jpg
DA-001-dog.jpg
DA-001-coffee.jpg
DA-002-house.jpg
DA-003-coffee.jpg
DA-003-cat.jpg
...

I want to generate this (CSV) output:

SKU, IMAGE
DA-001, "DA-001-car.jpg, DA-001-dog.jpg, DA-001-coffee.jpg"
DA-002, "DA-001-house.jpg"
DA-003, "DA-001-coffee.jpg, DA-001-cat.jpg"

I tried to program this in Bash:

#!/bin/bash
echo "SKU, FILE" >> tmp.csv
for file in /home/calvin/test/*.jpg
do
    SKU_NAME="${file##*/}"
    echo ${SKU_NAME:0:6}, \"inner for-loop?, ?, ?\" >> tmp.csv
done
uniq tmp.csv output.csv

As you can see I'm a noob as for programming :)
Please help me out, thanks in advance!

Body:
As result of all the replies and advises I'm using this code to achieve the desired output:

#!/bin/bash

echo "SKU, IMAGES" >> output.csv

ls *.jpg | cut -f1,2 -d- | sort -u | while read SKU
do
    echo $SKU, \"$(echo "$SKU"* | sed 's/ /, /g')\" >> output.csv
done

Thanks all!


问:
How to delete an item from a list inside of a class in python?
So i am building a shopping cart in python that has several commands such as add, remove, change, output item descriptions, output shopping cart, and quit(which terminates the function).

I am having trouble with removing an item from cart as my output is not the desired output.

So for example, for the input:

```<code>John Doe
February 1, 2016
a
Nike Romaleos
Volt color, Weightlifting shoes
189
2
a
Chocolate Chips
Semi-sweet
3
5
a
Powerbeats 2 Headphones
Bluetooth headphones
128
1
r
Chocolate Chips
o
q
</code>```

When it says r and then Chocolate Chips, Chocolate Chips should be removed from the Cart.

My code so far:

```<code>class ItemToPurchase:
    def __init__(self, item_name='none', item_price=0, item_quantity=0, item_description='none'):
        self.item_name = item_name
        self.item_price = item_price
        self.item_quantity = item_quantity
        self.item_description = item_description

    def print_item_cost(self):
        string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price,
                                            (self.item_quantity * self.item_price))
        cost = self.item_quantity * self.item_price
        return string, cost

    def print_item_description(self):
        string = '{}: {}'.format(self.item_name, self.item_description)
        print(string, end='\n')
        return string

class ShoppingCart:
    def __init__(self, customer_name='none', current_date='January 1, 2016', cart_items=[]):
        self.customer_name = customer_name
        self.current_date = current_date
        self.cart_items = cart_items

    def add_item(self, string):
        print('\nADD ITEM TO CART', end='\n')
        item_name = str(input('Enter the item name:'))
        item_description = str(input('\nEnter the item description:'))
        item_price = int(input('\nEnter the item price:'))
        item_quantity = int(input('\nEnter the item quantity:\n'))
        self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))

    def remove_item(self):
        print('\nREMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))
        i = 0
        for item in self.cart_items:
            if (item.item_name == string):
                del self.cart_items[i]
                i += 1
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing removed.')

    def modify_item(self):
        print('\nCHANGE ITEM QUANTITY', end='\n')
        name = str(input('Enter the item name: '))
        for item in self.cart_items:
            if (item.item_name == name):
                quantity = int(input('Enter the new quantity: '))
                item.item_quantity = quantity
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing modified.')

    def get_num_items_in_cart(self):
        num_items = 0
        for item in self.cart_items:
            num_items = num_items + item.item_quantity
        return num_items

    def get_cost_of_cart(self):
        total_cost = 0
        cost = 0
        for item in self.cart_items:

            cost = (item.item_quantity * item.item_price)

            total_cost += cost

        return total_cost

    def print_total(self):
        total_cost = self.get_cost_of_cart()
        if (total_cost == 0 and cost == 0):
            print('SHOPPING CART IS EMPTY')
        else:
            self.output_cart()

    def print_descriptions(self):
        print('\nOUTPUT ITEMS\' DESCRIPTIONS')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('\nItem Descriptions', end='\n')
        for item in self.cart_items:
            print('{}: {}'.format(item.item_name, item.item_description), end='\n')

    def output_cart(self):
        new = ShoppingCart()
        print('OUTPUT SHOPPING CART', end='\n')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')

        # IF NUMBER OF ITEMS IN THE OUTPUT CART IS 0...
        if new.get_num_items_in_cart() == 0:
            print('SHOPPING CART IS EMPTY')
        tc = 0
        for item in self.cart_items:
            print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity,
                                             item.item_price, (item.item_quantity * item.item_price)), end='\n')
            tc += (item.item_quantity * item.item_price)
        print('\nTotal: ${}'.format(tc), end='\n')

def print_menu(ShoppingCart):
    customer_Cart = newCart
    string = ''
    # declare the string menu
    menu = ('\nMENU\n'
            'a - Add item to cart\n'
            'r - Remove item from cart\n'
            'c - Change item quantity\n'
            'i - Output items\' descriptions\n'
            'o - Output shopping cart\n'
            'q - Quit\n')
    command = ''
    while (command != 'q'):
        string = ''
        print(menu, end='\n')
        command = input('Choose an option:\n')
        while (command != 'a' and command != 'o' and command != 'i' and command != 'r'
               and command != 'c' and command != 'q'):
            command = input('Choose an option:\n')
        if (command == 'a'):
            customer_Cart.add_item(string)
        if (command == 'o'):
            customer_Cart.output_cart()
        if (command == 'i'):
            customer_Cart.print_descriptions()
        if (command == 'r'):
            customer_Cart.remove_item()
        if (command == 'c'):
            customer_Cart.modify_item()

customer_name = str(input('Enter customer\'s name:'))
current_date = str(input('\nEnter today\'s date:\n\n'))
print('Customer name:', customer_name, end='\n')
print('Today\'s date:', current_date)
newCart = ShoppingCart(customer_name, current_date)
print_menu(newCart)
</code>```

I tried

```<code>def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))
    i = 0
    for item in self.cart_items:
        if (item.item_name == string):
            del self.cart_items[i]
            i += 1
            flag = True
            break
        else:
            flag = False
    if (flag == False):
        print('Item not found in cart. Nothing removed.')
</code>```

But my output (with the input) is:

```<code>REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 6

Chocolate Chips 5 @ $3 = $15
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $143

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
</code>```

When it should be:

```<code>REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 3

Nike Romaleos 2 @ $189 = $378
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $506

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
</code>```

As you can see, my code is deleting the Nike Romaleos, $189, at Quantity 2
When it should be deleting the Chocolate Chips, $3, at Quantity 5.
I am not sure why it is deleting the wrong items, as I inputted Chocolate Chips right after 'r', which calls the

```<code>if (command == 'r'):
    customer_Cart.remove_item()
</code>```

If anyone could help that would be greatly appreciated!

答:
In the remove_item method, you are using i as an index to the items. Every time you loop, you only increment the value of i if the item name matches with the input string. What you should be doing is increment i no matter if the condition evaluates to True or not because it is the index. So, just move the increment statement outside the conditional block.

def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))
    i = 0
    for item in self.cart_items:
        if (item.item_name == string):
            del self.cart_items[i]
            flag = True
            break
        else:
            flag = False
        i += 1
    if (flag == False):
        print('Item not found in cart. Nothing removed.')
```

<p>This is a common mistake that every programmer makes. So, Python has provided a more elegant way to access indices of the elements in the loop. </p>

<pre class="lang-py prettyprint-override"><code>def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))

    # We now don't need to handle the indices. Python will
    # do it for us. This magic happens with the help of `enumerate` function.
    for i, item in enumerate(self.cart_items):
        if (item.item_name == string):
            del self.cart_items[i]
            flag = True
            break
        else:
            flag = False
    if (flag == False):
        print('Item not found in cart. Nothing removed.')
</code>```

Body:
So i am building a shopping cart in python that has several commands such as add, remove, change, output item descriptions, output shopping cart, and quit(which terminates the function).

I am having trouble with removing an item from cart as my output is not the desired output.

So for example, for the input:

John Doe
February 1, 2016
a
Nike Romaleos
Volt color, Weightlifting shoes
189
2
a
Chocolate Chips
Semi-sweet
3
5
a
Powerbeats 2 Headphones
Bluetooth headphones
128
1
r
Chocolate Chips
o
q

When it says r and then Chocolate Chips, Chocolate Chips should be removed from the Cart.

My code so far:

class ItemToPurchase:
    def __init__(self, item_name='none', item_price=0, item_quantity=0, item_description='none'):
        self.item_name = item_name
        self.item_price = item_price
        self.item_quantity = item_quantity
        self.item_description = item_description

    def print_item_cost(self):
        string = '{} {} @ ${} = ${}'.format(self.item_name, self.item_quantity, self.item_price,
                                            (self.item_quantity * self.item_price))
        cost = self.item_quantity * self.item_price
        return string, cost

    def print_item_description(self):
        string = '{}: {}'.format(self.item_name, self.item_description)
        print(string, end='\n')
        return string

class ShoppingCart:
    def __init__(self, customer_name='none', current_date='January 1, 2016', cart_items=[]):
        self.customer_name = customer_name
        self.current_date = current_date
        self.cart_items = cart_items

    def add_item(self, string):
        print('\nADD ITEM TO CART', end='\n')
        item_name = str(input('Enter the item name:'))
        item_description = str(input('\nEnter the item description:'))
        item_price = int(input('\nEnter the item price:'))
        item_quantity = int(input('\nEnter the item quantity:\n'))
        self.cart_items.append(ItemToPurchase(item_name, item_price, item_quantity, item_description))

    def remove_item(self):
        print('\nREMOVE ITEM FROM CART', end='\n')
        string = str(input('Enter name of item to remove:\n'))
        i = 0
        for item in self.cart_items:
            if (item.item_name == string):
                del self.cart_items[i]
                i += 1
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing removed.')

    def modify_item(self):
        print('\nCHANGE ITEM QUANTITY', end='\n')
        name = str(input('Enter the item name: '))
        for item in self.cart_items:
            if (item.item_name == name):
                quantity = int(input('Enter the new quantity: '))
                item.item_quantity = quantity
                flag = True
                break
            else:
                flag = False
        if (flag == False):
            print('Item not found in cart. Nothing modified.')

    def get_num_items_in_cart(self):
        num_items = 0
        for item in self.cart_items:
            num_items = num_items + item.item_quantity
        return num_items

    def get_cost_of_cart(self):
        total_cost = 0
        cost = 0
        for item in self.cart_items:

            cost = (item.item_quantity * item.item_price)

            total_cost += cost

        return total_cost

    def print_total(self):
        total_cost = self.get_cost_of_cart()
        if (total_cost == 0 and cost == 0):
            print('SHOPPING CART IS EMPTY')
        else:
            self.output_cart()

    def print_descriptions(self):
        print('\nOUTPUT ITEMS\' DESCRIPTIONS')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('\nItem Descriptions', end='\n')
        for item in self.cart_items:
            print('{}: {}'.format(item.item_name, item.item_description), end='\n')

    def output_cart(self):
        new = ShoppingCart()
        print('OUTPUT SHOPPING CART', end='\n')
        print('{}\'s Shopping Cart - {}'.format(self.customer_name, self.current_date), end='\n')
        print('Number of Items:', new.get_num_items_in_cart(), end='\n\n')

        # IF NUMBER OF ITEMS IN THE OUTPUT CART IS 0...
        if new.get_num_items_in_cart() == 0:
            print('SHOPPING CART IS EMPTY')
        tc = 0
        for item in self.cart_items:
            print('{} {} @ ${} = ${}'.format(item.item_name, item.item_quantity,
                                             item.item_price, (item.item_quantity * item.item_price)), end='\n')
            tc += (item.item_quantity * item.item_price)
        print('\nTotal: ${}'.format(tc), end='\n')

def print_menu(ShoppingCart):
    customer_Cart = newCart
    string = ''
    # declare the string menu
    menu = ('\nMENU\n'
            'a - Add item to cart\n'
            'r - Remove item from cart\n'
            'c - Change item quantity\n'
            'i - Output items\' descriptions\n'
            'o - Output shopping cart\n'
            'q - Quit\n')
    command = ''
    while (command != 'q'):
        string = ''
        print(menu, end='\n')
        command = input('Choose an option:\n')
        while (command != 'a' and command != 'o' and command != 'i' and command != 'r'
               and command != 'c' and command != 'q'):
            command = input('Choose an option:\n')
        if (command == 'a'):
            customer_Cart.add_item(string)
        if (command == 'o'):
            customer_Cart.output_cart()
        if (command == 'i'):
            customer_Cart.print_descriptions()
        if (command == 'r'):
            customer_Cart.remove_item()
        if (command == 'c'):
            customer_Cart.modify_item()

customer_name = str(input('Enter customer\'s name:'))
current_date = str(input('\nEnter today\'s date:\n\n'))
print('Customer name:', customer_name, end='\n')
print('Today\'s date:', current_date)
newCart = ShoppingCart(customer_name, current_date)
print_menu(newCart)

I tried

def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))
    i = 0
    for item in self.cart_items:
        if (item.item_name == string):
            del self.cart_items[i]
            i += 1
            flag = True
            break
        else:
            flag = False
    if (flag == False):
        print('Item not found in cart. Nothing removed.')

But my output (with the input) is:

REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 6

Chocolate Chips 5 @ $3 = $15
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $143

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:

When it should be:

REMOVE ITEM FROM CART
Enter name of item to remove:

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:
OUTPUT SHOPPING CART
John Doe's Shopping Cart - February 1, 2016
Number of Items: 3

Nike Romaleos 2 @ $189 = $378
Powerbeats 2 Headphones 1 @ $128 = $128

Total: $506

MENU
a - Add item to cart
r - Remove item from cart
c - Change item quantity
i - Output items' descriptions
o - Output shopping cart
q - Quit

Choose an option:

As you can see, my code is deleting the Nike Romaleos, $189, at Quantity 2
When it should be deleting the Chocolate Chips, $3, at Quantity 5.
I am not sure why it is deleting the wrong items, as I inputted Chocolate Chips right after 'r', which calls the

if (command == 'r'):
    customer_Cart.remove_item()

If anyone could help that would be greatly appreciated!

Body:
In the remove_item method, you are using i as an index to the items. Every time you loop, you only increment the value of i if the item name matches with the input string. What you should be doing is increment i no matter if the condition evaluates to True or not because it is the index. So, just move the increment statement outside the conditional block.

def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))
    i = 0
    for item in self.cart_items:
        if (item.item_name == string):
            del self.cart_items[i]
            flag = True
            break
        else:
            flag = False
        i += 1
    if (flag == False):
        print('Item not found in cart. Nothing removed.')

This is a common mistake that every programmer makes. So, Python has provided a more elegant way to access indices of the elements in the loop.

def remove_item(self):
    print('\nREMOVE ITEM FROM CART', end='\n')
    string = str(input('Enter name of item to remove:\n'))

    # We now don't need to handle the indices. Python will
    # do it for us. This magic happens with the help of `enumerate` function.
    for i, item in enumerate(self.cart_items):
        if (item.item_name == string):
            del self.cart_items[i]
            flag = True
            break
        else:
            flag = False
    if (flag == False):
        print('Item not found in cart. Nothing removed.')


问:
How To Display Images Picked From File Picker In Flutter
I am using file picker plugin to pick images I want to display the picked images on the screen below is my code Am able to pick image name and path and display them as text in my app but unable to display them as images, After I display those image then I want to upload the image to the firebase storage.

```<code>import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String _fileName;
  String _path;
  Map<String, String> _paths;
  String _extension;
  bool _loadingPath = false;
  bool _multiPick = false;
  FileType _pickingType = FileType.any;
  TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.addListener(() => _extension = _controller.text);
  }

  void _openFileExplorer() async {
    setState(() => _loadingPath = true);
    try {
      if (_multiPick) {
        _path = null;
        _paths = await FilePicker.getMultiFilePath(
            type: _pickingType,
            allowedExtensions: (_extension?.isNotEmpty ?? false)
                ? _extension?.replaceAll(' ', '')?.split(',')
                : null);
      } else {
        _paths = null;
        _path = await FilePicker.getFilePath(
            type: _pickingType,
            allowedExtensions: (_extension?.isNotEmpty ?? false)
                ? _extension?.replaceAll(' ', '')?.split(',')
                : null);
      }
    } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    }
    if (!mounted) return;
    setState(() {
      _loadingPath = false;
      _fileName = _path != null
          ? _path.split('/').last
          : _paths != null ? _paths.keys.toString() : '...';
    });
  }

  void _clearCachedFiles() {
    FilePicker.clearTemporaryFiles().then((result) {
      _scaffoldKey.currentState.showSnackBar(
        SnackBar(
          backgroundColor: result ? Colors.green : Colors.red,
          content: Text((result
              ? 'Temporary files removed with success.'
              : 'Failed to clean temporary files')),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
          title: const Text('File Picker example app'),
        ),
        body: new Center(
            child: new Padding(
              padding: const EdgeInsets.only(left: 10.0, right: 10.0),
              child: new SingleChildScrollView(
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new Padding(
                      padding: const EdgeInsets.only(top: 20.0),
                      child: new DropdownButton(
                          hint: new Text('LOAD PATH FROM'),
                          value: _pickingType,
                          items: <DropdownMenuItem>[
                            new DropdownMenuItem(
                              child: new Text('FROM AUDIO'),
                              value: FileType.audio,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM IMAGE'),
                              value: FileType.image,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM VIDEO'),
                              value: FileType.video,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM MEDIA'),
                              value: FileType.media,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM ANY'),
                              value: FileType.any,
                            ),
                            new DropdownMenuItem(
                              child: new Text('CUSTOM FORMAT'),
                              value: FileType.custom,
                            ),
                          ],
                          onChanged: (value) => setState(() {
                            _pickingType = value;
                            if (_pickingType != FileType.custom) {
                              _controller.text = _extension = '';
                            }
                          })),
                    ),
                    new ConstrainedBox(
                      constraints: BoxConstraints.tightFor(width: 100.0),
                      child: _pickingType == FileType.custom
                          ? new TextFormField(
                        maxLength: 15,
                        autovalidate: true,
                        controller: _controller,
                        decoration:
                        InputDecoration(labelText: 'File extension'),
                        keyboardType: TextInputType.text,
                        textCapitalization: TextCapitalization.none,
                      )
                          : new Container(),
                    ),
                    new ConstrainedBox(
                      constraints: BoxConstraints.tightFor(width: 200.0),
                      child: new SwitchListTile.adaptive(
                        title: new Text('Pick multiple files',
                            textAlign: TextAlign.right),
                        onChanged: (bool value) =>
                            setState(() => _multiPick = value),
                        value: _multiPick,
                      ),
                    ),
                    new Padding(
                      padding: const EdgeInsets.only(top: 50.0, bottom: 20.0),
                      child: Column(
                        children: <Widget>[
                          new RaisedButton(
                            onPressed: () => _openFileExplorer(),
                            child: new Text("Open file picker"),
                          ),
                          new RaisedButton(
                            onPressed: () => _clearCachedFiles(),
                            child: new Text("Clear temporary files"),
                          ),
                        ],
                      ),
                    ),
                    new Builder(
                      builder: (BuildContext context) => _loadingPath
                          ? Padding(
                          padding: const EdgeInsets.only(bottom: 10.0),
                          child: const CircularProgressIndicator())
                          : _path != null || _paths != null
                          ? new Container(
                        padding: const EdgeInsets.only(bottom: 30.0),
                        height: MediaQuery.of(context).size.height * 0.50,
                        child: new Scrollbar(
                            child: new ListView.separated(
                              itemCount: _paths != null && _paths.isNotEmpty
                                  ? _paths.length
                                  : 1,
                              itemBuilder: (BuildContext context, int index) {
                                final bool isMultiPath =
                                    _paths != null && _paths.isNotEmpty;
                                final String name = 'File $index: ' +
                                    (isMultiPath
                                        ? _paths.keys.toList()[index]
                                        : _fileName ?? '...');
                                final path = isMultiPath
                                    ? _paths.values.toList()[index].toString()
                                    : _path;

                                return new ListTile(
                                  title: new Text(
                                    name,
                                  ),
                                  subtitle: new Text(_path),
                                );
                              },
                              separatorBuilder:
                                  (BuildContext context, int index) =>
                              new Divider(),
                            )),
                      )
                          : new Container(),
                    ),
                  ],
                ),
              ),
            )),
      ),
    );
  }
}
</code>```

答:
You can display the image like this:</p>

```<code>Image.file(
  File(_path),
  fit: BoxFit.cover,
  width: double.infinity,
)
</code>```

Body:
I am using file picker plugin to pick images I want to display the picked images on the screen below is my code Am able to pick image name and path and display them as text in my app but unable to display them as images, After I display those image then I want to upload the image to the firebase storage.

import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String _fileName;
  String _path;
  Map<String, String> _paths;
  String _extension;
  bool _loadingPath = false;
  bool _multiPick = false;
  FileType _pickingType = FileType.any;
  TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.addListener(() => _extension = _controller.text);
  }

  void _openFileExplorer() async {
    setState(() => _loadingPath = true);
    try {
      if (_multiPick) {
        _path = null;
        _paths = await FilePicker.getMultiFilePath(
            type: _pickingType,
            allowedExtensions: (_extension?.isNotEmpty ?? false)
                ? _extension?.replaceAll(' ', '')?.split(',')
                : null);
      } else {
        _paths = null;
        _path = await FilePicker.getFilePath(
            type: _pickingType,
            allowedExtensions: (_extension?.isNotEmpty ?? false)
                ? _extension?.replaceAll(' ', '')?.split(',')
                : null);
      }
    } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    }
    if (!mounted) return;
    setState(() {
      _loadingPath = false;
      _fileName = _path != null
          ? _path.split('/').last
          : _paths != null ? _paths.keys.toString() : '...';
    });
  }

  void _clearCachedFiles() {
    FilePicker.clearTemporaryFiles().then((result) {
      _scaffoldKey.currentState.showSnackBar(
        SnackBar(
          backgroundColor: result ? Colors.green : Colors.red,
          content: Text((result
              ? 'Temporary files removed with success.'
              : 'Failed to clean temporary files')),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
          title: const Text('File Picker example app'),
        ),
        body: new Center(
            child: new Padding(
              padding: const EdgeInsets.only(left: 10.0, right: 10.0),
              child: new SingleChildScrollView(
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new Padding(
                      padding: const EdgeInsets.only(top: 20.0),
                      child: new DropdownButton(
                          hint: new Text('LOAD PATH FROM'),
                          value: _pickingType,
                          items: <DropdownMenuItem>[
                            new DropdownMenuItem(
                              child: new Text('FROM AUDIO'),
                              value: FileType.audio,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM IMAGE'),
                              value: FileType.image,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM VIDEO'),
                              value: FileType.video,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM MEDIA'),
                              value: FileType.media,
                            ),
                            new DropdownMenuItem(
                              child: new Text('FROM ANY'),
                              value: FileType.any,
                            ),
                            new DropdownMenuItem(
                              child: new Text('CUSTOM FORMAT'),
                              value: FileType.custom,
                            ),
                          ],
                          onChanged: (value) => setState(() {
                            _pickingType = value;
                            if (_pickingType != FileType.custom) {
                              _controller.text = _extension = '';
                            }
                          })),
                    ),
                    new ConstrainedBox(
                      constraints: BoxConstraints.tightFor(width: 100.0),
                      child: _pickingType == FileType.custom
                          ? new TextFormField(
                        maxLength: 15,
                        autovalidate: true,
                        controller: _controller,
                        decoration:
                        InputDecoration(labelText: 'File extension'),
                        keyboardType: TextInputType.text,
                        textCapitalization: TextCapitalization.none,
                      )
                          : new Container(),
                    ),
                    new ConstrainedBox(
                      constraints: BoxConstraints.tightFor(width: 200.0),
                      child: new SwitchListTile.adaptive(
                        title: new Text('Pick multiple files',
                            textAlign: TextAlign.right),
                        onChanged: (bool value) =>
                            setState(() => _multiPick = value),
                        value: _multiPick,
                      ),
                    ),
                    new Padding(
                      padding: const EdgeInsets.only(top: 50.0, bottom: 20.0),
                      child: Column(
                        children: <Widget>[
                          new RaisedButton(
                            onPressed: () => _openFileExplorer(),
                            child: new Text("Open file picker"),
                          ),
                          new RaisedButton(
                            onPressed: () => _clearCachedFiles(),
                            child: new Text("Clear temporary files"),
                          ),
                        ],
                      ),
                    ),
                    new Builder(
                      builder: (BuildContext context) => _loadingPath
                          ? Padding(
                          padding: const EdgeInsets.only(bottom: 10.0),
                          child: const CircularProgressIndicator())
                          : _path != null || _paths != null
                          ? new Container(
                        padding: const EdgeInsets.only(bottom: 30.0),
                        height: MediaQuery.of(context).size.height * 0.50,
                        child: new Scrollbar(
                            child: new ListView.separated(
                              itemCount: _paths != null && _paths.isNotEmpty
                                  ? _paths.length
                                  : 1,
                              itemBuilder: (BuildContext context, int index) {
                                final bool isMultiPath =
                                    _paths != null && _paths.isNotEmpty;
                                final String name = 'File $index: ' +
                                    (isMultiPath
                                        ? _paths.keys.toList()[index]
                                        : _fileName ?? '...');
                                final path = isMultiPath
                                    ? _paths.values.toList()[index].toString()
                                    : _path;

                                return new ListTile(
                                  title: new Text(
                                    name,
                                  ),
                                  subtitle: new Text(_path),
                                );
                              },
                              separatorBuilder:
                                  (BuildContext context, int index) =>
                              new Divider(),
                            )),
                      )
                          : new Container(),
                    ),
                  ],
                ),
              ),
            )),
      ),
    );
  }
}

Body:
You can display the image like this:

Image.file(
  File(_path),
  fit: BoxFit.cover,
  width: double.infinity,
)


答:
The logic of following code in remove_item is wrong:

```<code>for item in self.cart_items:
    if (item.item_name == string):
        del self.cart_items[i]
        i += 1 # you only inc i when it match the string
        # also after delete, the index may be not consistent.
        flag = True
        break
    else:
        flag = False # you didn't inc i here.
</code>```

you can use:

```<code>self.cart_items = [item for item in self.cart_items if item.item_name != string]
</code>```

Title: How to delete an item from a list inside of a class in python?

Body:
The logic of following code in remove_item is wrong:

for item in self.cart_items:
    if (item.item_name == string):
        del self.cart_items[i]
        i += 1 # you only inc i when it match the string
        # also after delete, the index may be not consistent.
        flag = True
        break
    else:
        flag = False # you didn't inc i here.

you can use:

self.cart_items = [item for item in self.cart_items if item.item_name != string]


问:
extend functionality of UIAlertView?
I am using a UIAlertView with a message Peer Disconnected.Back ground works/remaining codes are working without dismiss it.there is a button called Continue. I need to work the remaining codes only after the continue button click.
and also I need to Quit my application in cancel button click.can any one tell me a good way to do it.

My Code is:

```<code>UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];
</code>```

答:
```<code>UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];
</code>```

Implement this delegate method.

```<code>-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == alertView.cancelButtonIndex) {
// Cancel operation...
}else if (buttonIndex == alertView.firstOtherButtonIndex) {
// Continue operation...
}
}
</code>```

Title: extend functionality of UIAlertView?

Body:
I am using a UIAlertView with a message Peer Disconnected.Back ground works/remaining codes are working without dismiss it.there is a button called Continue. I need to work the remaining codes only after the continue button click.
and also I need to Quit my application in cancel button click.can any one tell me a good way to do it.

My Code is:

UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];

Body:
UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];

Implement this delegate method.

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == alertView.cancelButtonIndex) {
// Cancel operation...
}else if (buttonIndex == alertView.firstOtherButtonIndex) {
// Continue operation...
}
}


问:
Invariant Violation: requireNativeComponent: "RNCSafeAreaProvider" was not found in the UIManager
Implementing React Navigate in the project installing the package npm install @react-navigation/native @react-navigation/stack shows the following error.

Can anyone help me with this issue?

答:
expo update did not work for me unfortunately :(

When running yarn start in my console, I got:

```<code>Some of your project's dependencies are not compatible with currently installed expo package version:
 - react-native-reanimated - expected version range: ~1.7.0 - actual version installed: ^1.9.0
 - react-native-screens - expected version range: ~2.2.0 - actual version installed: ^2.8.0
 - react-native-safe-area-context - expected version range: 0.7.3 - actual version installed: ^3.0.2
 - @react-native-community/masked-view - expected version range: 0.1.6 - actual version installed: ^0.1.10
Your project may not work correctly until you install the correct versions of the packages.
To install the correct versions of these packages, please run: expo install [package-name ...]
</code>```

I ran expo install <package>@<version> for each of the shown packages, and it is working now!

Body:
expo update did not work for me unfortunately :(

When running yarn start in my console, I got:

Some of your project's dependencies are not compatible with currently installed expo package version:
 - react-native-reanimated - expected version range: ~1.7.0 - actual version installed: ^1.9.0
 - react-native-screens - expected version range: ~2.2.0 - actual version installed: ^2.8.0
 - react-native-safe-area-context - expected version range: 0.7.3 - actual version installed: ^3.0.2
 - @react-native-community/masked-view - expected version range: 0.1.6 - actual version installed: ^0.1.10
Your project may not work correctly until you install the correct versions of the packages.
To install the correct versions of these packages, please run: expo install [package-name ...]

I ran expo install <package>@<version> for each of the shown packages, and it is working now!


问:
How to convert Bitmap to Image
I am making a median filter, the problem is manipulating pixes are only possible in Bitmap. Later I want to show the result in a PictureBox which uses Image. I can't figure out a way to to solve this...Only thing I can think of is using a Stream but no idea how. Help will be appriciated~

```<code>private void toolStripPerformMedian_Click(object sender, EventArgs e)
{
    var filtered = Filters.MedianFilter(new Bitmap(_activeImageFile), 3);
    var n = Image.FromStream() //How to do this?
}
</code>```

答:
This is what has worked for me:</p>
```<code>var codeBitmap = new Bitmap(your_info);
Image image = (Image)codeBitmap;
</code>```

Title: How to convert Bitmap to Image

Body:
I am making a median filter, the problem is manipulating pixes are only possible in Bitmap. Later I want to show the result in a PictureBox which uses Image. I can't figure out a way to to solve this...Only thing I can think of is using a Stream but no idea how. Help will be appriciated~

private void toolStripPerformMedian_Click(object sender, EventArgs e)
{
    var filtered = Filters.MedianFilter(new Bitmap(_activeImageFile), 3);
    var n = Image.FromStream() //How to do this?
}

Body:
This is what has worked for me:

var codeBitmap = new Bitmap(your_info);
Image image = (Image)codeBitmap;


问:
Variable inside if statement in javaScript
I wonder why my first code doesn't work and the second does. I thought they're basically the same....
Looks like var inside if statement doesn't seem to be processed as expected. Could anyone please clarify why it doesn't work?

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var letterCheck = myFarm[i].charAt(0);

for (var i = 0; i < myFarm.length; i++) {
    console.log(i);
}

if (letterCheck === "c" || letterCheck === "o") {
    alert("Starts with 'c' or 'o'!");
}
```

<hr>

<pre class="lang-js prettyprint-override"><code>var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var arrayLength = myFarm.length;

for (var j = 0; j < arrayLength; j++) {

    console.log(myFarm[j]);

    if (myFarm[j].charAt(0) === "c" || myFarm[j].charAt(0) === "o") {

        alert("Starts with a c or an o!");
    }

}
</code>```

答: The first code is trying to get the position [i] from the array, but the variable i does not exist there, it is created in the for loop that is below.</p>

Body:
I wonder why my first code doesn't work and the second does. I thought they're basically the same....
Looks like var inside if statement doesn't seem to be processed as expected. Could anyone please clarify why it doesn't work?

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var letterCheck = myFarm[i].charAt(0);

for (var i = 0; i < myFarm.length; i++) {
    console.log(i);
}

if (letterCheck === "c" || letterCheck === "o") {
    alert("Starts with 'c' or 'o'!");
}

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var arrayLength = myFarm.length;

for (var j = 0; j < arrayLength; j++) {

    console.log(myFarm[j]);

    if (myFarm[j].charAt(0) === "c" || myFarm[j].charAt(0) === "o") {

        alert("Starts with a c or an o!");
    }

}


答:
This is a good reason to avoid var in favor of let or const when writing modern JavaScript: confusion around hoisting.  With var declarations, the declaration is hoisted to the top of the scope but the assignment doesn't get hoisted; it occurs at the line at which it is assigned in the code as written.  So we can see if we add a console log:

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];

console.log(i)

var letterCheck = myFarm[i].charAt(0);

for (var i = 0; i < myFarm.length; i++) {
    console.log(i);
}

if (letterCheck === "c" || letterCheck === "o") {
    alert("Starts with 'c' or 'o'!");
}```

... that i is undefined at the time you try to use it to get an index off an array.

Title: Variable inside if statement in javaScript

Body:
This is a good reason to avoid var in favor of let or const when writing modern JavaScript: confusion around hoisting.  With var declarations, the declaration is hoisted to the top of the scope but the assignment doesn't get hoisted; it occurs at the line at which it is assigned in the code as written.  So we can see if we add a console log:

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];

console.log(i)

var letterCheck = myFarm[i].charAt(0);

for (var i = 0; i < myFarm.length; i++) {
    console.log(i);
}

if (letterCheck === "c" || letterCheck === "o") {
    alert("Starts with 'c' or 'o'!");
}

... that i is undefined at the time you try to use it to get an index off an array.