问:
In Python Selenium, how to wait for either two elements to be found and continue with the loop
In order to get the text I want

d1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/table[1]/tbody/tr'))).text

I need to wait for either wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item'))) or wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.related-keyword-item'))) to be uploaded with certain text value to get d1.

Above ky  is the code for entering the page, my problem is the code below ky.

If wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item'))) is  not  found, it will wait for wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.related-keyword-item'))). But I don't want to wait for 60 seconds to continue to wait for second element if there is already no first element.

And if I add more than thousands of keywords in ky, this will appear raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: try

I have tried to fix this problem more than a week and I'm desperate for someone to help me out.
This is my code and the code works well only with hundreds of keywords in ky.

```<code>import xlrd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome(executable_path=r"C:\Users\Kim woo jae\PycharmProjects\100개 키워드\chromedriver.exe")
list = []
list1 = []
list2 = []
list3 = []

driver.get("https://itemscout.io/keyword/")
wait = WebDriverWait(driver, 60)
b = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[2]/input')))
b.clear()
b.send_keys('화장대')
c = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[2]/span')))
c.click()
d = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[ @id="container"]/table[1]/tbody/tr'))).text

ky = '화장대','침대전신거울','서랍장','까사마루3단행거','옷장', '5단서랍장','6평농막'

for k in ky:
    b1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[1]/input')))
    b1.clear()
    b1.send_keys(k)
    c1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[1]/span')))
    c1.click()
    time.sleep(1)
    try:
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item')))
    except:
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.related-keyword-item')))
    d1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/table[1]/tbody/tr'))).text
    d1 = (d1).replace(',', '.')
    d1 = ' '.join(d1.splitlines())
    d1 = d1.replace(' ', ',')
    result = [x.strip() for x in d1.split(',')]

    d = [result[2]]
    s = [result[3]]
    c = [result[4]]
    print([k],d,s,c)
</code>```

答:
You can use or , in the CSS_SELECTOR. It will return the first if found, else the second. It will check for both every the DOM is pulled

```<code>wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item, span.related-keyword-item')))
</code>```

Body:
In order to get the text I want

d1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/table[1]/tbody/tr'))).text

I need to wait for either wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item'))) or wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.related-keyword-item'))) to be uploaded with certain text value to get d1.

Above ky  is the code for entering the page, my problem is the code below ky.

If wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item'))) is  not  found, it will wait for wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.related-keyword-item'))). But I don't want to wait for 60 seconds to continue to wait for second element if there is already no first element.

And if I add more than thousands of keywords in ky, this will appear raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: try

I have tried to fix this problem more than a week and I'm desperate for someone to help me out.
This is my code and the code works well only with hundreds of keywords in ky.

import xlrd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome(executable_path=r"C:\Users\Kim woo jae\PycharmProjects\100개 키워드\chromedriver.exe")
list = []
list1 = []
list2 = []
list3 = []

driver.get("https://itemscout.io/keyword/")
wait = WebDriverWait(driver, 60)
b = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[2]/input')))
b.clear()
b.send_keys('화장대')
c = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[2]/span')))
c.click()
d = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[ @id="container"]/table[1]/tbody/tr'))).text

ky = '화장대','침대전신거울','서랍장','까사마루3단행거','옷장', '5단서랍장','6평농막'

for k in ky:
    b1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[1]/input')))
    b1.clear()
    b1.send_keys(k)
    c1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[1]/span')))
    c1.click()
    time.sleep(1)
    try:
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item')))
    except:
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'span.related-keyword-item')))
    d1 = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/table[1]/tbody/tr'))).text
    d1 = (d1).replace(',', '.')
    d1 = ' '.join(d1.splitlines())
    d1 = d1.replace(' ', ',')
    result = [x.strip() for x in d1.split(',')]

    d = [result[2]]
    s = [result[3]]
    c = [result[4]]
    print([k],d,s,c)

Body:
You can use or , in the CSS_SELECTOR. It will return the first if found, else the second. It will check for both every the DOM is pulled

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.related-keyword-item, span.related-keyword-item')))


来源: stackexchange

问:
Align the bottom of a child element with the parent's baseline
I would like to vertically align a child element in a flex box (or text box) so that its bottom coincides with the baseline of its siblings.

This happens by default for images:

MDN  Element:

 has no baseline, so when images are used in an inline formatting context with vertical-align: baseline, the bottom of the image will be placed on the text baseline.

Can I achieve the same effect with a
 instead of an ?

Later edit: I'm attaching a snippet. I want the bottom border of the last child to coincide with the bottom border of the image (the baseline of the rest of the children). I don't want everything aligned to the bottom.

.parent {
    display: flex;
    align-items: baseline;
}

.child2 {
    font-family: monospace;
    font-size: 200%;
}

img {
    border-bottom: 1px solid red;
}

.child-bottom {
    padding: 5px;
    background-color: #fdd;
    border-bottom: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <span>These</span>
    <span class="child2">are</span>
    <span>baseline</span>
    <img src="https://cdn.sstatic.net/Img/ico-binoculars.svg?v=d4dbaac4eec9">
    <span>aligned.</span>
    <div class="child-bottom">This child's bottom border should be on the baseline of the parent.</div>
</div></code>```

Later edit 2. A picture is a thousand words. Hope it helps clarify what kind of alignment I need. Notice how letters j, p, and q extend below the baseline.

答:
Finally, I found a solution:) It was hidden somewhere in the CSS specification:

The baseline of an 'inline-block' is the baseline of its last line box
  in the normal flow, unless it has either no in-flow line boxes or if
  its 'overflow' property has a computed value other than 'visible', in
  which case the baseline is the bottom margin edge.

This is taken from https://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align, bottom of the page.

So, in order to move its baseline to the bottom margin edge, you only have to add display: inline-block and overflow: hidden (or anything other than 'visible', eg: 'auto') to the child element:

body {
    font-size: 200%;
}

.bottom {
    display: inline-block; /* <--- this */
    overflow: hidden; /* <--- and this */

    width: 10rem;
    border: 2px solid orange;
    padding: 2rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <span>text jklmnopqr</span>
    <div class="bottom">div with bottom on the baseline</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to vertically align a child element in a flex box (or text box) so that its bottom coincides with the baseline of its siblings.

This happens by default for images:

MDN  Element:

 has no baseline, so when images are used in an inline formatting context with vertical-align: baseline, the bottom of the image will be placed on the text baseline.

Can I achieve the same effect with a
 instead of an ?

Later edit: I'm attaching a snippet. I want the bottom border of the last child to coincide with the bottom border of the image (the baseline of the rest of the children). I don't want everything aligned to the bottom.

.parent {
    display: flex;
    align-items: baseline;
}

.child2 {
    font-family: monospace;
    font-size: 200%;
}

img {
    border-bottom: 1px solid red;
}

.child-bottom {
    padding: 5px;
    background-color: #fdd;
    border-bottom: 1px solid red;
}

    These
    are
    baseline

    aligned.

This child's bottom border should be on the baseline of the parent.

Later edit 2. A picture is a thousand words. Hope it helps clarify what kind of alignment I need. Notice how letters j, p, and q extend below the baseline.

Body:
Finally, I found a solution:) It was hidden somewhere in the CSS specification:

The baseline of an 'inline-block' is the baseline of its last line box
  in the normal flow, unless it has either no in-flow line boxes or if
  its 'overflow' property has a computed value other than 'visible', in
  which case the baseline is the bottom margin edge.

This is taken from https://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align, bottom of the page.

So, in order to move its baseline to the bottom margin edge, you only have to add display: inline-block and overflow: hidden (or anything other than 'visible', eg: 'auto') to the child element:

body {
    font-size: 200%;
}

.bottom {
    display: inline-block; /* <--- this */
    overflow: hidden; /* <--- and this */

    width: 10rem;
    border: 2px solid orange;
    padding: 2rem;
}

<div>
    <span>text jklmnopqr</span>
    <div class="bottom">div with bottom on the baseline</div>
</div>


问:
Formula to convert matrix to rows in Google Sheets
I'm trying to concatenate rows of a matrix in a spreadsheet, which I've got from an importhtml call.

For example, if I have a 3x3 table:

```<code>A   B   C
D   E   F
G   H   I
</code>```

I would like a command/function to convert it a row like so:

```<code>A B C D E F G H I
</code>```

The idea is that each line will have a different html form which the same table/data is meant to be extracted. This cannot be done manually each time.

答:
replace A1:C3 with your IMPORTHTML formula:

```<code>=SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(A1:C3),,999^99)),,999^99), " ")
</code>```

if it contains words / spaces:

```<code>=ARRAYFORMULA(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(
 SUBSTITUTE(A1:C3, " ", CHAR(127))),,999^99)),,999^99), " "))
</code>```

Body:
I'm trying to concatenate rows of a matrix in a spreadsheet, which I've got from an importhtml call.

For example, if I have a 3x3 table:

A   B   C
D   E   F
G   H   I

I would like a command/function to convert it a row like so:

A B C D E F G H I

The idea is that each line will have a different html form which the same table/data is meant to be extracted. This cannot be done manually each time.

Body:
replace A1:C3 with your IMPORTHTML formula:

=SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(A1:C3),,999^99)),,999^99), " ")

if it contains words / spaces:

=ARRAYFORMULA(SPLIT(QUERY(TRANSPOSE(QUERY(TRANSPOSE(
 SUBSTITUTE(A1:C3, " ", CHAR(127))),,999^99)),,999^99), " "))


问:
Run a Python script from PackageMaker in OSX
I'm having a difficult time finding any decent documentation for packaging on OSX. My package needs to run a Python script that will do some launchd magic right after the app is installed. I tried using -s scripts with packagemaker and put my script in the directory scripts, but I had no luck. Is there something I'm missing? More importantly, where is all the packagemaker documentation? How can I get my Python script to run? The only thing I've seen is this, which is way outdated and doesn't cover the command line version.

I don't want to use the GUI; it makes my life too difficult.

答:
I've resolved this issue.

The script needs to be named postflight and have a proper shebang line.

The script needs to exit with specific status codes (0 for success, which is the default, I believe).

ContentLicense: CC BY-SA 3.0


问:
VBA error 1004 and source file become read only
I am trying to read two pages ("SYN" and "STR") of an excel file into two different arrays.

the code is very simple, and it works just fine if i only need one page :

```<code>Sub recap()
Dim wb As Workbook
Dim fpath As String
fpath = Application.ActiveProject.Path & "\Suivi d'études.xlsm"
'(this is the file I want to read in the same folder)

Set wb = Workbooks.Open(fpath, True, False)

Dim rng1 As Range
Dim i, j As Integer

i = wb.Worksheets("STR").UsedRange.Rows.Count
j = wb.Worksheets("STR").Columns.Count

Set rng1 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Dim data2(), data1() As Variant
data1() = rng1

wb.Close

Debug.Print (data1(10, 10))

End Sub
</code>```

it works just fine.
Then I intergrated the seconde page.

```<code>Sub recap()

Dim wb As Workbook   'Need Microsoft Excel 16.0 Object Library
Dim fpath As String
fpath = Application.ActiveProject.Path & "\Suivi d'études.xlsm"

Set wb = Workbooks.Open(fpath, True, False)

Dim rng1, rng2 As Range
Dim i, j, a, b As Integer

a = wb.Worksheets("SYN").UsedRange.Rows.Count
b = wb.Worksheets("SYN").Columns.Count

i = wb.Worksheets("STR").UsedRange.Rows.Count
j = wb.Worksheets("STR").Columns.Count

Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
Set rng2 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Dim data2(), data1() As Variant
data1() = rng1
data2() = rng2
wb.Close
Debug.Print (data2(10, 10))
End Sub
</code>```

Not only it gaves me 1004 error on the range setting line: set rng1 = blablabla, but also since the code is not fully executed, the input excel file is still "open" in the code, it became a read-only file.

So my questions are:
1. which could cause this error, why can't they read the seconde page in an array?
2. how to force the input file to "close" if wb.close was not executed?

答:
The problem here is how you define your variables. In your first code you did:

```<code>Dim rng1 As Range
'
'
'
Set rng1 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))
</code>```

Because rng1 has been created as a Range Object, yes, you need to set it up with Set.

In your second code you did:

```<code>Dim rng1, rng2 As Range
'
'
'
'
Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
Set rng2 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))
</code>```

Notice that only rng2 is being defined as a Range Object. Variable rng1 is being defined as Variant, the default option in VBA when you don't specify a type.

So VBA thinks rng1 is a Variant and then later on you do:

```<code>Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
</code>```

And that raises an error because Set must be used only with objects.

VBA, because rng1 has been defined as Variant, was expecting a line like:

rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))

This means you are taking all those values in that range into a bidimensional array named rng1. You don't want to do this, but this explains why VBA raises that error.

The solution is really easy. Just define always what type of variables/objects you are using.

Line Dim rng1 as Range, rng2 As Range should fix your problem. Always declare properly all your variables.

Hope this helps.

Body:
I am trying to read two pages ("SYN" and "STR") of an excel file into two different arrays.

the code is very simple, and it works just fine if i only need one page :

Sub recap()
Dim wb As Workbook
Dim fpath As String
fpath = Application.ActiveProject.Path & "\Suivi d'études.xlsm"
'(this is the file I want to read in the same folder)

Set wb = Workbooks.Open(fpath, True, False)

Dim rng1 As Range
Dim i, j As Integer

i = wb.Worksheets("STR").UsedRange.Rows.Count
j = wb.Worksheets("STR").Columns.Count

Set rng1 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Dim data2(), data1() As Variant
data1() = rng1

wb.Close

Debug.Print (data1(10, 10))

End Sub

it works just fine.
Then I intergrated the seconde page.

Sub recap()

Dim wb As Workbook   'Need Microsoft Excel 16.0 Object Library
Dim fpath As String
fpath = Application.ActiveProject.Path & "\Suivi d'études.xlsm"

Set wb = Workbooks.Open(fpath, True, False)

Dim rng1, rng2 As Range
Dim i, j, a, b As Integer

a = wb.Worksheets("SYN").UsedRange.Rows.Count
b = wb.Worksheets("SYN").Columns.Count

i = wb.Worksheets("STR").UsedRange.Rows.Count
j = wb.Worksheets("STR").Columns.Count

Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
Set rng2 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Dim data2(), data1() As Variant
data1() = rng1
data2() = rng2
wb.Close
Debug.Print (data2(10, 10))
End Sub

Not only it gaves me 1004 error on the range setting line: set rng1 = blablabla, but also since the code is not fully executed, the input excel file is still "open" in the code, it became a read-only file.

So my questions are:
1. which could cause this error, why can't they read the seconde page in an array?
2. how to force the input file to "close" if wb.close was not executed?

Body:
The problem here is how you define your variables. In your first code you did:

Dim rng1 As Range
'
'
'
Set rng1 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Because rng1 has been created as a Range Object, yes, you need to set it up with Set.

In your second code you did:

Dim rng1, rng2 As Range
'
'
'
'
Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))
Set rng2 = wb.Worksheets("STR").Range(Cells(1, 1), Cells(i, j))

Notice that only rng2 is being defined as a Range Object. Variable rng1 is being defined as Variant, the default option in VBA when you don't specify a type.

So VBA thinks rng1 is a Variant and then later on you do:

Set rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))

And that raises an error because Set must be used only with objects.

VBA, because rng1 has been defined as Variant, was expecting a line like:

rng1 = wb.Worksheets("SYN").Range(Cells(1, 1), Cells(a, b))

This means you are taking all those values in that range into a bidimensional array named rng1. You don't want to do this, but this explains why VBA raises that error.

The solution is really easy. Just define always what type of variables/objects you are using.

Line Dim rng1 as Range, rng2 As Range should fix your problem. Always declare properly all your variables.

Hope this helps.


问:
F# compilation error related to inheritance
I have 2 interfaces defined in a C# component, where 1 interface inherits from another generic interface

```<code>public interface IRepository<T>
{
void Add(T obj);
void Update(T obj);
void Delete(T obj);
}
public interface IDataModelRepository :
    IRepository<DataModel>
{
}
</code>```

I have an F# component where I define a generic type with a constructor parameter with the generic interface:

```<code>type Domain<T> ( getRepository:System.Func<IRepository<T>>) = ...
</code>```

Then I define a derived type using the derived interface:

```<code>type DataModelDomain ( getRepository:System.Func<IDataModelRepository>) =
inherit Domain<DataModel> (getRepository)
</code>```

This does not compile giving the error message on the DataModelDomain type:

The type 'IRepository' does not match the type 'IDataModelRepository'

However if I define those 'Domain' types in classes in a C# component in a similar way, it does compile. Is there a way to define the DataModelDomain type deriving from the generic Domain type and using the derived interface IDataModelRepository

答:
I think I managed to reproduce the problem in compiling F# code. And then fixed it by creating a new function, calling the other one inside it, and safely upcasting the result: (fun () -> getRepository.Invoke() :> IRepository<DataModel>)

Here's the whole thing:

```<code>type DataModel = DataModel

type IRepository<'T> =
    abstract member Add: 'T -> unit
    abstract member Update : 'T -> unit
    abstract member Delete : 'T -> unit

type IDataModelRepository =
    inherit IRepository<DataModel>

type Domain<'T> ( getRepository:System.Func<IRepository<'T>>) =
    do ()

type DataModelDomain ( getRepository:System.Func<IDataModelRepository>) =
    inherit Domain<DataModel> (fun () -> getRepository.Invoke() :> IRepository<DataModel>)
    do ()
</code>```

Body:
I have 2 interfaces defined in a C# component, where 1 interface inherits from another generic interface

public interface IRepository<T>
{
void Add(T obj);
void Update(T obj);
void Delete(T obj);
}
public interface IDataModelRepository :
    IRepository<DataModel>
{
}

I have an F# component where I define a generic type with a constructor parameter with the generic interface:

type Domain<T> ( getRepository:System.Func<IRepository<T>>) = ...

Then I define a derived type using the derived interface:

type DataModelDomain ( getRepository:System.Func<IDataModelRepository>) =
inherit Domain<DataModel> (getRepository)

This does not compile giving the error message on the DataModelDomain type:

The type 'IRepository' does not match the type 'IDataModelRepository'

However if I define those 'Domain' types in classes in a C# component in a similar way, it does compile. Is there a way to define the DataModelDomain type deriving from the generic Domain type and using the derived interface IDataModelRepository

Body:
I think I managed to reproduce the problem in compiling F# code. And then fixed it by creating a new function, calling the other one inside it, and safely upcasting the result: (fun () -> getRepository.Invoke() :> IRepository<DataModel>)

Here's the whole thing:

type DataModel = DataModel

type IRepository<'T> =
    abstract member Add: 'T -> unit
    abstract member Update : 'T -> unit
    abstract member Delete : 'T -> unit

type IDataModelRepository =
    inherit IRepository<DataModel>

type Domain<'T> ( getRepository:System.Func<IRepository<'T>>) =
    do ()

type DataModelDomain ( getRepository:System.Func<IDataModelRepository>) =
    inherit Domain<DataModel> (fun () -> getRepository.Invoke() :> IRepository<DataModel>)
    do ()


问:
Macro to Filter Multiple Column and between Value
I have table like this

and i want to filter base on this criteria

VAlue = between 2000 and 3000

Status = 'FALSE'

become like this, the filter on Column F & G

and this is my code

```<code>Dim LastRow As Long
Dim i, Hide, popup  As Long
Dim message  As String
Dim LRow As Long
Dim sht As Worksheet
ActiveSheet.AutoFilterMode = False
    Columns.EntireColumn.Hidden = False
    Rows.EntireRow.Hidden = False
   Columns("O:R").EntireColumn.Delete
    Range("O:R").EntireColumn.Insert
    Range("F1").Value = "PO sTATUS"
    Range("G1").Value = "Value"

Set sht = ActiveSheet
LastRow = sht.Range("B" & Rows.Count).End(xlUp).Row

With sht.Range("F1:F" & LastRow)
    .Formula = "=B1"
   .Value = .Value
    .AutoFilter field:=1, Criteria1:="FALSE"
  End With

With sht.Range("G1:G" & LastRow)
    .Formula = "=D1"
   .Value = .Value
 .AutoFilter field:=1, Criteria1:=">=2000", Operator:=xlAnd, Criteria2:="<=3000"

   End With
</code>```

and this code always show only Row 1 no values

答:
Try applying the filter all at once?</p>

```<code>Dim LastRow As Long
Dim i, Hide, popup  As Long
Dim message  As String
Dim LRow As Long
Dim sht As Worksheet

    ActiveSheet.AutoFilterMode = False
    Columns.EntireColumn.Hidden = False
    Rows.EntireRow.Hidden = False
    Columns("O:R").EntireColumn.Delete
    Range("O:R").EntireColumn.Insert
    Range("F1").Value = "PO sTATUS"
    Range("G1").Value = "Value"

Set sht = ActiveSheet
LastRow = sht.Range("B" & Rows.Count).End(xlUp).Row

With sht.Range("F1:F" & LastRow)
    .Formula = "=B1"
    .Value = .Value
End With

With sht.Range("G1:G" & LastRow)
    .Formula = "=D1"
    .Value = .Value
End With

With sht.Range("F1:G" & LastRow)
    .AutoFilter
    .AutoFilter field:=1, Criteria1:="FALSE"
    .AutoFilter field:=2, Criteria1:=">=2000", Operator:=xlAnd, Criteria2:="<=3000"
End With
</code>```

Body:
I have table like this

and i want to filter base on this criteria

VAlue = between 2000 and 3000

Status = 'FALSE'

become like this, the filter on Column F & G

and this is my code

Dim LastRow As Long
Dim i, Hide, popup  As Long
Dim message  As String
Dim LRow As Long
Dim sht As Worksheet
ActiveSheet.AutoFilterMode = False
    Columns.EntireColumn.Hidden = False
    Rows.EntireRow.Hidden = False
   Columns("O:R").EntireColumn.Delete
    Range("O:R").EntireColumn.Insert
    Range("F1").Value = "PO sTATUS"
    Range("G1").Value = "Value"

Set sht = ActiveSheet
LastRow = sht.Range("B" & Rows.Count).End(xlUp).Row

With sht.Range("F1:F" & LastRow)
    .Formula = "=B1"
   .Value = .Value
    .AutoFilter field:=1, Criteria1:="FALSE"
  End With

With sht.Range("G1:G" & LastRow)
    .Formula = "=D1"
   .Value = .Value
 .AutoFilter field:=1, Criteria1:=">=2000", Operator:=xlAnd, Criteria2:="<=3000"

   End With

and this code always show only Row 1 no values

Body:
Try applying the filter all at once?

Dim LastRow As Long
Dim i, Hide, popup  As Long
Dim message  As String
Dim LRow As Long
Dim sht As Worksheet

    ActiveSheet.AutoFilterMode = False
    Columns.EntireColumn.Hidden = False
    Rows.EntireRow.Hidden = False
    Columns("O:R").EntireColumn.Delete
    Range("O:R").EntireColumn.Insert
    Range("F1").Value = "PO sTATUS"
    Range("G1").Value = "Value"

Set sht = ActiveSheet
LastRow = sht.Range("B" & Rows.Count).End(xlUp).Row

With sht.Range("F1:F" & LastRow)
    .Formula = "=B1"
    .Value = .Value
End With

With sht.Range("G1:G" & LastRow)
    .Formula = "=D1"
    .Value = .Value
End With

With sht.Range("F1:G" & LastRow)
    .AutoFilter
    .AutoFilter field:=1, Criteria1:="FALSE"
    .AutoFilter field:=2, Criteria1:=">=2000", Operator:=xlAnd, Criteria2:="<=3000"
End With


问:
Looking for a regex pattern between a range of 0.1 to 24. Need to allow for 2 decimal places
I can't seem to get a regex to work that will allow a user to enter a float between the range of 0.1 to 24.  I need to allow 2 decimal places and it must be greater than 0 and less than 24.    </p>

答:
Thanks for all the responses!

I missed typed early and the acceptable range should be >= .01 and <= 24.  Below are other restrictions...

Leading zero is optional values less than 1

Decimal is optional but only allow 2 entries

0, 0.0, 0.00, .0, .00 is not allowed


问:
Generate unique integer with 8 digits in java
I'm trying to figure how to approach with generating unique integer with 8 digits in java. The biggest problem is that it gives you a limited permutation, and also the clustered env. Any suggestion is welcome.

Regards

答:
```<code>    int[] result = new Random().ints(10_000_000, 100_000_000)
            .distinct()
            .limit(8)
            .toArray();
</code>```

8 digits starts with 10_000_000 upto inclusive 99_999_999.
The large range means that duplicates are rear, so the internal looping will rarely be idle, have conflicting duplicates.

Clustered usage: easiest is to use a database.

Body:
    int[] result = new Random().ints(10_000_000, 100_000_000)
            .distinct()
            .limit(8)
            .toArray();

8 digits starts with 10_000_000 upto inclusive 99_999_999.
The large range means that duplicates are rear, so the internal looping will rarely be idle, have conflicting duplicates.

Clustered usage: easiest is to use a database.


问:
How to echo names of last upload file
I was asked that the output file should only output the name and id of the last person who uploaded a file with a specific name. confusing right? even I am confused. so let me give an example

let us say that you have 3 employees registered in your company. lets call them

Pikachu,

Raichu and

Pichu.

Pikachu has 3 files uploaded in the company, Raichu has 2 files uploaded and Pichu has also 2 files uploaded. The files must also be ordered according to employeename(ASC) and filename(DESC). Mine is already in ordered by. This is my only problem. In this case the output should look like this:

*noticed that the employee name and employee id is in the last file uploaded?? does anyone knows how to do that?please i beg you guys to help me out here T-T the task is way too hard and im just a rookie

Im thinking of using 2 tables here. table 1 for the employee id and employee name, table 2 for the file name, etc. so i guess this would also involve 2 while clause. i have the idea but i dont know how to mix them all up.

my code before I edited it like sir vincent look like this:

```<code>if ($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa'
   OR $_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
{

  $sql= "select * from gmdc_employee
         where employee_name like '%$search%'
         AND employee_name like '$listname%'";
} else {
  $sql = "select b.* from gmdc_user a, gmdc_employee b
          where a.username = '".$_SESSION[$fgmembersite->GetLoginSessionVar()]."'
          AND a.company_id = b.company_id
          AND b.employee_name like '$listname%'
          AND b.employee_name like '%$search%'";
}
$query = mysql_query("$sql ORDER BY employee_name,confirmation DESC
                     ,file_id DESC,file_date DESC
                      LIMIT $offset,$limit") or die ( mysql_error () );
$result = mysql_query($sql) or die (mysql_error());
$total = mysql_num_rows($result);

if(!$result || mysql_num_rows($result) <= 0)
{
  $fgmembersite->HandleError("No file found.");
  return false;
}
while ($row = mysql_fetch_assoc($query))
{
  $file_id = $row['file_id'];
  $file_desc = $row['file_description'];
  $file_date = $row['file_date'];
  $file_name = $row['file_name'];
  $file_accs = $row['folder_access'];
  $file_employee  = $row['employee_id'];
  $file_confir = $row['confirmation'];
  $file_ename = ucwords($row['employee_name']);

  $info = pathinfo($file_name);
  $file_ext = $info['extension'];

  echo '<tr><td> </td></tr>
        <tr class="subone"><td class="sub" width="100">'.$file_employee.'<br />
         </td>';
  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    ?>
    <td class="sub" width="100">
    <a href="" onclick = javascript:newPopup('addfile.php?emp=
    <?php echo $file_employee ?>');><?php echo$file_ename?></a>
    <br /> </td>
    <?php
  } else {
    echo '<td class="sub" width="182">'.$file_ename.'<br /> </td>';
  }
  echo'<td  class="sub" width="218">
       <a href="'.$file_accs.$file_name.'" target="_blank"
        style="text-decoration: underline;">'.$file_desc.'</a>
       <br /> </td><td  class="sub" width="100">
      '.date('M d, Y',mktime(0,0,0,substr($file_date,5,2)
       ,substr($file_date,8,2),substr($file_date,0,4))).'
       <br /> </td><td  class="sub" width="100">'.$file_confir.'
       <br /> </td>';

  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    if($file_confir == 'Pending' OR $file_confir == 'NotApproved')
    {
      if(isset($_GET['id']))
      {
        $fgmembersite->Delete_Db($_GET['id']);
      }
      echo '<td  class="sub" width="100">
            <a href="index.php?id='.$file_id.'">Delete</a>
            <br /> </td>';
    }
  }
  else if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
  {
    if($file_confir == 'Pending')
      {
        if(isset($_GET['yes']))
        {
          $fgmembersite->UpdateYesDB($_GET['yes']);
          //echo "<script>location.reload();</script>";
        }
        else if(isset($_GET['no']))
        {
          $fgmembersite->UpdateNoDB($_GET['no']);
          //echo "<script>location.reload();</script>";
        }
        if (!isset($_GET['offset'])) {
          $prevoffset = 0;
        } else {
          $prevoffset = $_GET['offset'];
          echo'<td  class="sub" width="100">
          <a href="index.php?offset='.$prevoffset.'&searchfile='.$search.'
           &namelist='.$listname.'&yes='.$file_id.'">Approve</a>
           //there's a link here<br /><br />
           <a href="index.php?offset='.$prevoffset.'&searchfile='.$search.'
            &namelist='.$listname.'&no='.$file_id.'">NotApprove</a>
            //there's a link here
             </td> ';
      }
    }
  }?>
</code>```

Just ignore every if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin') and whatever, this is for different output since my file can be logged into by 3 different users. SA(programmers), admin(the approver of the file uploaded), and user(company). There are TD and TR there as well, I don't know why wont it appear here.

output looked like this:

```<code>employee_id  +   employee_name  +  file_name
3            |   pichu          |  file6
3            |   pichu          |  file1
1            |   pikachu        |  file7
1            |   pikachu        |  file4
1            |   pikachi        |  file3
2            |   raichu         |  file8
2            |   raichu         |  file5
2            |   raichu         |  file2
</code>```

and I want my output to be like this:

```<code>***OUTPUT***

**employee_id        employee_name              file_name**
    3                      pichu                        file6
                                                        file1
    1                     pikachu                       file7
                                                        file4
                                                        file3
    2                     raichu                        file5
                                                        file2
</code>```

for example that raichu uploaded another file, the output should now look like this:

OUTPUT

```<code>**employee_id        employee_name            file_name**
    3                      pichu                      file6
                                                      file1
    1                      pikachu                    file7
                                                      file4
                                                      file3
    2                      raichu                     file8
                                                      file5
                                                      file2
</code>```

答:
Using Vincent table structure will likely solve your problem. And to get the result you wanted, you can use single query using join for the two table. So there's no need to use two query.

```<code>SELECT  e.employee_id as employee_id,            //Display column for employee_id
        e.employee_name as employee_name,
        f.file_name as file_name
  FROM employee e                                // The e is an alias for table
 INNER JOIN file f                               // The inner join will return all the rows which have same employee_id on both table
    ON e.employee_id = f.employee_id
 ORDER BY e.employee_name, f.file_name DESC;     // Order of the result default is ASC
</code>```

UPDATE

I assume you have two tables and the structure is same with Vincent. Now This query will get the data on two tables. The join part here is that, when an employee_id  on employee table has a same employee_id on the file table, this will return a row. Please see mysql join for more information. Then the order e.employee_id is the employee_id on employee table, since there's no order specified it will use the default which is ascending.

Then output of the above query could be the below code.

```<code>employee_id  +   employee_name  +  file_name
3            |   pichu          |  file6
3            |   pichu          |  file1
1            |   pikachu        |  file7
1            |   pikachu        |  file4
1            |   pikachi        |  file3
2            |   raichu         |  file8
2            |   raichu         |  file5
2            |   raichu         |  file2
</code>```

You will notice that employee_id and employee_name is repeated. This is because the query include all the columns value in a row that specified in SELECT column_name. You can filter the duplicate value in your php, specially if you will store it first in an object rather than directly printing it.

PHP

```<code>$query = $see_the_query_above;
$result = mysql_query($query) or die(mysql_error($db));
$emp_id = "";     //This will be use to remove employee_id if its already echoed.
$emp_name = "";   //This will be use to remove employee_name if its already echoed.

echo '<table>';
echo '<tr><th>employee_id</th><th>employee_name</th><th>file_name</th></tr>';

while ($row = mysql_fetch_assoc($result)) {
    //Check $emp_id and $emp_name if same with the current, if same just print nothing or space else replace it with new.
    $emp_id = $emp_id == $row['employee_id'] ? "" : $row['employee_id']
    $emp_name = $emp_name == $row['employee_name'] ? "" : $row['employee_name'];

    echo '<tr>';
    echo '<td>'.$emp_id.'<td>';
    echo '<td>'.$emp_name.'</td>';
    echo '<td>'.$row['file_name'].'</td>';
    echo '</tr>';
}
echo '</table>';
</code>```

Title: How to echo names of last upload file

Body:
I was asked that the output file should only output the name and id of the last person who uploaded a file with a specific name. confusing right? even I am confused. so let me give an example

let us say that you have 3 employees registered in your company. lets call them

Pikachu,

Raichu and

Pichu.

Pikachu has 3 files uploaded in the company, Raichu has 2 files uploaded and Pichu has also 2 files uploaded. The files must also be ordered according to employeename(ASC) and filename(DESC). Mine is already in ordered by. This is my only problem. In this case the output should look like this:

*noticed that the employee name and employee id is in the last file uploaded?? does anyone knows how to do that?please i beg you guys to help me out here T-T the task is way too hard and im just a rookie

Im thinking of using 2 tables here. table 1 for the employee id and employee name, table 2 for the file name, etc. so i guess this would also involve 2 while clause. i have the idea but i dont know how to mix them all up.

my code before I edited it like sir vincent look like this:

if ($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa'
   OR $_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
{

  $sql= "select * from gmdc_employee
         where employee_name like '%$search%'
         AND employee_name like '$listname%'";
} else {
  $sql = "select b.* from gmdc_user a, gmdc_employee b
          where a.username = '".$_SESSION[$fgmembersite->GetLoginSessionVar()]."'
          AND a.company_id = b.company_id
          AND b.employee_name like '$listname%'
          AND b.employee_name like '%$search%'";
}
$query = mysql_query("$sql ORDER BY employee_name,confirmation DESC
                     ,file_id DESC,file_date DESC
                      LIMIT $offset,$limit") or die ( mysql_error () );
$result = mysql_query($sql) or die (mysql_error());
$total = mysql_num_rows($result);

if(!$result || mysql_num_rows($result) <= 0)
{
  $fgmembersite->HandleError("No file found.");
  return false;
}
while ($row = mysql_fetch_assoc($query))
{
  $file_id = $row['file_id'];
  $file_desc = $row['file_description'];
  $file_date = $row['file_date'];
  $file_name = $row['file_name'];
  $file_accs = $row['folder_access'];
  $file_employee  = $row['employee_id'];
  $file_confir = $row['confirmation'];
  $file_ename = ucwords($row['employee_name']);

  $info = pathinfo($file_name);
  $file_ext = $info['extension'];

  echo '

'.$file_employee.'

         	';
  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    ?>

    <a href="" onclick = javascript:newPopup('addfile.php?emp=
    <?php echo $file_employee ?>');><?php echo$file_ename?>

    <?php
  } else {
    echo ''.$file_ename.'
 	';
  }
  echo'
       '.$file_desc.'

      '.date('M d, Y',mktime(0,0,0,substr($file_date,5,2)
       ,substr($file_date,8,2),substr($file_date,0,4))).'

 	'.$file_confir.'

 	';

  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    if($file_confir == 'Pending' OR $file_confir == 'NotApproved')
    {
      if(isset($_GET['id']))
      {
        $fgmembersite->Delete_Db($_GET['id']);
      }
      echo '
            Delete

 	';
    }
  }
  else if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
  {
    if($file_confir == 'Pending')
      {
        if(isset($_GET['yes']))
        {
          $fgmembersite->UpdateYesDB($_GET['yes']);
          //echo "";
        }
        else if(isset($_GET['no']))
        {
          $fgmembersite->UpdateNoDB($_GET['no']);
          //echo "";
        }
        if (!isset($_GET['offset'])) {
          $prevoffset = 0;
        } else {
          $prevoffset = $_GET['offset'];
          echo'
          Approve
           //there's a link here

           NotApprove
            //there's a link here
             	 ';
      }
    }
  }?>

Just ignore every if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin') and whatever, this is for different output since my file can be logged into by 3 different users. SA(programmers), admin(the approver of the file uploaded), and user(company). There are TD and TR there as well, I don't know why wont it appear here.

output looked like this:

employee_id  +   employee_name  +  file_name
3            |   pichu          |  file6
3            |   pichu          |  file1
1            |   pikachu        |  file7
1            |   pikachu        |  file4
1            |   pikachi        |  file3
2            |   raichu         |  file8
2            |   raichu         |  file5
2            |   raichu         |  file2

and I want my output to be like this:

***OUTPUT***

**employee_id        employee_name              file_name**
    3                      pichu                        file6
                                                        file1
    1                     pikachu                       file7
                                                        file4
                                                        file3
    2                     raichu                        file5
                                                        file2

for example that raichu uploaded another file, the output should now look like this:

OUTPUT

**employee_id        employee_name            file_name**
    3                      pichu                      file6
                                                      file1
    1                      pikachu                    file7
                                                      file4
                                                      file3
    2                      raichu                     file8
                                                      file5
                                                      file2

Body:
Using Vincent table structure will likely solve your problem. And to get the result you wanted, you can use single query using join for the two table. So there's no need to use two query.

SELECT  e.employee_id as employee_id,            //Display column for employee_id
        e.employee_name as employee_name,
        f.file_name as file_name
  FROM employee e                                // The e is an alias for table
 INNER JOIN file f                               // The inner join will return all the rows which have same employee_id on both table
    ON e.employee_id = f.employee_id
 ORDER BY e.employee_name, f.file_name DESC;     // Order of the result default is ASC

UPDATE

I assume you have two tables and the structure is same with Vincent. Now This query will get the data on two tables. The join part here is that, when an employee_id  on employee table has a same employee_id on the file table, this will return a row. Please see mysql join for more information. Then the order e.employee_id is the employee_id on employee table, since there's no order specified it will use the default which is ascending.

Then output of the above query could be the below code.

employee_id  +   employee_name  +  file_name
3            |   pichu          |  file6
3            |   pichu          |  file1
1            |   pikachu        |  file7
1            |   pikachu        |  file4
1            |   pikachi        |  file3
2            |   raichu         |  file8
2            |   raichu         |  file5
2            |   raichu         |  file2

You will notice that employee_id and employee_name is repeated. This is because the query include all the columns value in a row that specified in SELECT column_name. You can filter the duplicate value in your php, specially if you will store it first in an object rather than directly printing it.

PHP

$query = $see_the_query_above;
$result = mysql_query($query) or die(mysql_error($db));
$emp_id = "";     //This will be use to remove employee_id if its already echoed.
$emp_name = "";   //This will be use to remove employee_name if its already echoed.

echo '<table>';
echo '<tr><th>employee_id</th><th>employee_name</th><th>file_name</th></tr>';

while ($row = mysql_fetch_assoc($result)) {
    //Check $emp_id and $emp_name if same with the current, if same just print nothing or space else replace it with new.
    $emp_id = $emp_id == $row['employee_id'] ? "" : $row['employee_id']
    $emp_name = $emp_name == $row['employee_name'] ? "" : $row['employee_name'];

    echo '<tr>';
    echo '<td>'.$emp_id.'<td>';
    echo '<td>'.$emp_name.'</td>';
    echo '<td>'.$row['file_name'].'</td>';
    echo '</tr>';
}
echo '</table>';


问:
pyqtgraph: problem setting smooth=False on a GLSurfacePlotItem object
I'm currently trying to plot a basic color-coded 'slice' in 3D using pyqtgraph. When I initialize the GLSurfacePlotItem object with smooth=True everything works fine. However I get a massive amount of errors and warnings when I simply set smooth=False. Unfortunately the documentation does not really explain much about this setting.

Below is my example code. What am I missing?

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg

x, y, z = 30, 20, 10
data = np.random.rand(x,y,z)

cmap = matplotlib.cm.get_cmap('jet')
norm = matplotlib.colors.PowerNorm(vmin=0.0, vmax=1.0, gamma=2.5)
m = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap)

colors = np.zeros((x,y,z,4), dtype=np.float16)
for i in range(x):
    colors[i,:,:,:] = m.to_rgba(data[i,:,:])

app = QtGui.QApplication(sys.argv)
w = gl.GLViewWidget()

zslice = gl.GLSurfacePlotItem(x=np.arange(0,x,1), y=np.arange(0,y,1), z=np.ones((x,y))*0.5, colors=colors[:,:,0,:], smooth=True, computeNormals=False)

w.addItem(zslice)
w.setGeometry(100, 10, 1280, 720)
w.show()

if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
    QtGui.QApplication.instance().exec_()
</code>```

The error message I get when I set smooth=False:

```<code>[13:16:04]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.
[13:16:04]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.
[13:16:04]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.
[13:16:06]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.
</code>```

答: The error says "IndexError: index 30 is out of bounds for axis 0 with size 30," which suggests that you or the library you are using might be looping 1 through 30 instead of 0 through 29. (Setting smooth=False might send your code to the portion of the library withe the error in it.) Since your x variable is 30, I'm guessing that's the point of origin. The error message says the issue is in ./test5.py", line 34, so I would start there.</p>

Body:
I'm currently trying to plot a basic color-coded 'slice' in 3D using pyqtgraph. When I initialize the GLSurfacePlotItem object with smooth=True everything works fine. However I get a massive amount of errors and warnings when I simply set smooth=False. Unfortunately the documentation does not really explain much about this setting.

Below is my example code. What am I missing?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg

x, y, z = 30, 20, 10
data = np.random.rand(x,y,z)

cmap = matplotlib.cm.get_cmap('jet')
norm = matplotlib.colors.PowerNorm(vmin=0.0, vmax=1.0, gamma=2.5)
m = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap)

colors = np.zeros((x,y,z,4), dtype=np.float16)
for i in range(x):
    colors[i,:,:,:] = m.to_rgba(data[i,:,:])

app = QtGui.QApplication(sys.argv)
w = gl.GLViewWidget()

zslice = gl.GLSurfacePlotItem(x=np.arange(0,x,1), y=np.arange(0,y,1), z=np.ones((x,y))*0.5, colors=colors[:,:,0,:], smooth=True, computeNormals=False)

w.addItem(zslice)
w.setGeometry(100, 10, 1280, 720)
w.show()

if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
    QtGui.QApplication.instance().exec_()

The error message I get when I set smooth=False:

[13:16:04]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.
[13:16:04]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.
[13:16:04]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.
[13:16:06]

    |==============================>>
    |  Traceback (most recent call last):
    |    File "./test5.py", line 34, in <module>
    |      QtGui.QApplication.instance().exec_()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 179, in paintGL
    |      self.drawItemTree(useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 219, in drawItemTree
    |      self.drawItemTree(i, useItemNames=useItemNames)
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 200, in drawItemTree
    |      debug.printExc()
    |    --- exception caught here ---
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/GLViewWidget.py", line 197, in drawItemTree
    |      i.paint()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 167, in paint
    |      self.parseMeshData()
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/items/GLMeshItem.py", line 151, in parseMeshData
    |      self.colors = md.vertexColors(indexed='faces')
    |    File "/home/steve/anaconda3/lib/python3.7/site-packages/pyqtgraph/opengl/MeshData.py", line 239, in vertexColors
    |      self._vertexColorsIndexedByFaces = self._vertexColors[self.faces()]
    |  IndexError: index 30 is out of bounds for axis 0 with size 30
    |==============================<<
Error while drawing item <pyqtgraph.opengl.items.GLSurfacePlotItem.GLSurfacePlotItem object at 0x7f9f0cf21410>.


问:
API level 29 Intent.ACTION_GET_CONTENT returning wrong id from downloads folder
I am trying to find the full file path for an URI returned from file picker intent. I have downloaded an image from internet which was saved in the browser default download folder. The problem is the id returned by DocumentsContract.getDocumentId(content_describer) is like "msf:254" instead of Long type id generally returned. The code is as following

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
        Uri content_describer = data.getData();
        String src = content_describer.getPath();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
            imgView.setImageBitmap(bitmap);
        }catch(Exception e){

        }

        Log.e("selected file", content_describer.toString());
        String filename = content_describer.getLastPathSegment();
        Log.e("selected path", filename);
        Log.e("authority",content_describer.getAuthority());

        if (content_describer.getAuthority().equals("com.android.externalstorage.documents")) {
            final String docId = DocumentsContract.getDocumentId(content_describer);
            final String[] split = docId.split(":");
            final String type = split[0];
            Log.e("npath", "getPath() docId: " + docId + ", split: " + split.length + ", type: " + type);
            if ("primary".equalsIgnoreCase(type)) {
                if (split.length > 1) {
                    Log.e("nnpath1", Environment.getExternalStorageDirectory() + "/" + split[1]);
                    curFile = Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    Log.e("nnpath2", Environment.getExternalStorageDirectory() + "/");
                }
                // This is for checking SD Card
            } else {
                Log.e("nnpath3", "storage" + "/" + docId.replace(":", "/"));
                curFile = "storage" + "/" + docId.replace(":", "/");
            }
        }

        if (content_describer.getAuthority().equals("com.android.providers.downloads.documents")) {
            final String docId = DocumentsContract.getDocumentId(content_describer);
            Log.e("docid",docId);

            Uri ci = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));

            final String column = "_data";
            final String[] projection = {
                    column
            };
            Cursor cursor10 = getActivity().getApplicationContext().getContentResolver().query(ci, projection, null, null,
                    null);
            if (cursor10 != null && cursor10.moveToFirst()) {

                final int column_index = cursor10.getColumnIndexOrThrow(column);
                Log.e("imgpp", cursor10.getString(column_index));
                Log.e("imgpp2", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath());
                File fn = new File(cursor10.getString(column_index));
                Log.e("imgpp3", fn.getPath());
                curFile = fn.getPath();
            }
        }

        if (content_describer.getAuthority().equals("com.android.providers.media.documents")) {
            final String docId = DocumentsContract.getDocumentId(content_describer);
            Log.e("docid", docId);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            final String column = "_data";
            final String[] projection = {
                    column
            };
            Cursor cursor1 = getActivity().getApplicationContext().getContentResolver().query(contentUri, projection, selection, selectionArgs,
                    null);
            if (cursor1 != null && cursor1.moveToFirst()) {

                final int column_index = cursor1.getColumnIndexOrThrow(column);
                Log.e("imgpp", cursor1.getString(column_index));
                Log.e("imgpp2", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath());
                File fn = new File(cursor1.getString(column_index));
                Log.e("imgpp3", fn.getPath());
                curFile = fn.getPath();
            }
        }

        Log.e("final path",curFile);

    }
}
</code>```

Please note if I pick the same image going via Image->Downwnload, the above code works normally but when same file is picked from Downloads folder, following error is thrown

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.flexi.app.android, PID: 15414
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=196709, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/msf:253 flg=0x1 }} to activity {com.flexi.app.android/com.flexi.app.android.ProfileActivity}: java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/253
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4830)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4871)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7319)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
 Caused by: java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/253
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:170)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:423)
    at android.content.ContentResolver.query(ContentResolver.java:934)
    at android.content.ContentResolver.query(ContentResolver.java:872)
    at android.content.ContentResolver.query(ContentResolver.java:830)
    at com.flexi.app.android.fragments.ProfileImageFragment.onActivityResult(ProfileImageFragment.java:171)
    at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:170)
    at com.flexi.app.android.ProfileActivity.onActivityResult(ProfileActivity.java:28)
    at android.app.Activity.dispatchActivityResult(Activity.java:8091)
</code>```

The URI is reported as content://com.android.providers.downloads.documents/document/msf%3A253
Any idea what is msf? I have seen image, video, audo but noticed msf for first time.

答:
I found the way from comment section. Thanks to @blackapps.

```<code> val inputStream = context!!.contentResolver.openInputStream(data.data!!)
 val docFile =File("${activity!!.cacheDir}/doc_${sharedPreferences.getString("applno", "")}.pdf")
 if (!docFile.exists()) {
        docFile.createNewFile()
 }
</code>```

copyStreamToFile(inputStream!!,docFile)

```<code>private fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
    inputStream.use { input ->
        val outputStream = FileOutputStream(outputFile)
        outputStream.use { output ->
            val buffer = ByteArray(4 * 1024) // buffer size
            while (true) {
                val byteCount = input.read(buffer)
                if (byteCount < 0) break
                output.write(buffer, 0, byteCount)
            }
            output.flush()
        }
    }
}
</code>```

Body:
I am trying to find the full file path for an URI returned from file picker intent. I have downloaded an image from internet which was saved in the browser default download folder. The problem is the id returned by DocumentsContract.getDocumentId(content_describer) is like "msf:254" instead of Long type id generally returned. The code is as following

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
        Uri content_describer = data.getData();
        String src = content_describer.getPath();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
            imgView.setImageBitmap(bitmap);
        }catch(Exception e){

        }

        Log.e("selected file", content_describer.toString());
        String filename = content_describer.getLastPathSegment();
        Log.e("selected path", filename);
        Log.e("authority",content_describer.getAuthority());

        if (content_describer.getAuthority().equals("com.android.externalstorage.documents")) {
            final String docId = DocumentsContract.getDocumentId(content_describer);
            final String[] split = docId.split(":");
            final String type = split[0];
            Log.e("npath", "getPath() docId: " + docId + ", split: " + split.length + ", type: " + type);
            if ("primary".equalsIgnoreCase(type)) {
                if (split.length > 1) {
                    Log.e("nnpath1", Environment.getExternalStorageDirectory() + "/" + split[1]);
                    curFile = Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    Log.e("nnpath2", Environment.getExternalStorageDirectory() + "/");
                }
                // This is for checking SD Card
            } else {
                Log.e("nnpath3", "storage" + "/" + docId.replace(":", "/"));
                curFile = "storage" + "/" + docId.replace(":", "/");
            }
        }

        if (content_describer.getAuthority().equals("com.android.providers.downloads.documents")) {
            final String docId = DocumentsContract.getDocumentId(content_describer);
            Log.e("docid",docId);

            Uri ci = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));

            final String column = "_data";
            final String[] projection = {
                    column
            };
            Cursor cursor10 = getActivity().getApplicationContext().getContentResolver().query(ci, projection, null, null,
                    null);
            if (cursor10 != null && cursor10.moveToFirst()) {

                final int column_index = cursor10.getColumnIndexOrThrow(column);
                Log.e("imgpp", cursor10.getString(column_index));
                Log.e("imgpp2", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath());
                File fn = new File(cursor10.getString(column_index));
                Log.e("imgpp3", fn.getPath());
                curFile = fn.getPath();
            }
        }

        if (content_describer.getAuthority().equals("com.android.providers.media.documents")) {
            final String docId = DocumentsContract.getDocumentId(content_describer);
            Log.e("docid", docId);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            final String column = "_data";
            final String[] projection = {
                    column
            };
            Cursor cursor1 = getActivity().getApplicationContext().getContentResolver().query(contentUri, projection, selection, selectionArgs,
                    null);
            if (cursor1 != null && cursor1.moveToFirst()) {

                final int column_index = cursor1.getColumnIndexOrThrow(column);
                Log.e("imgpp", cursor1.getString(column_index));
                Log.e("imgpp2", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath());
                File fn = new File(cursor1.getString(column_index));
                Log.e("imgpp3", fn.getPath());
                curFile = fn.getPath();
            }
        }

        Log.e("final path",curFile);

    }
}

Please note if I pick the same image going via Image->Downwnload, the above code works normally but when same file is picked from Downloads folder, following error is thrown

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.flexi.app.android, PID: 15414
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=196709, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/msf:253 flg=0x1 }} to activity {com.flexi.app.android/com.flexi.app.android.ProfileActivity}: java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/253
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4830)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4871)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2009)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7319)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
 Caused by: java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/253
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:170)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:423)
    at android.content.ContentResolver.query(ContentResolver.java:934)
    at android.content.ContentResolver.query(ContentResolver.java:872)
    at android.content.ContentResolver.query(ContentResolver.java:830)
    at com.flexi.app.android.fragments.ProfileImageFragment.onActivityResult(ProfileImageFragment.java:171)
    at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:170)
    at com.flexi.app.android.ProfileActivity.onActivityResult(ProfileActivity.java:28)
    at android.app.Activity.dispatchActivityResult(Activity.java:8091)

The URI is reported as content://com.android.providers.downloads.documents/document/msf%3A253
Any idea what is msf? I have seen image, video, audo but noticed msf for first time.

Body:
I found the way from comment section. Thanks to @blackapps.

 val inputStream = context!!.contentResolver.openInputStream(data.data!!)
 val docFile =File("${activity!!.cacheDir}/doc_${sharedPreferences.getString("applno", "")}.pdf")
 if (!docFile.exists()) {
        docFile.createNewFile()
 }

copyStreamToFile(inputStream!!,docFile)

private fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
    inputStream.use { input ->
        val outputStream = FileOutputStream(outputFile)
        outputStream.use { output ->
            val buffer = ByteArray(4 * 1024) // buffer size
            while (true) {
                val byteCount = input.read(buffer)
                if (byteCount < 0) break
                output.write(buffer, 0, byteCount)
            }
            output.flush()
        }
    }
}


问:
Convert doc and docx to images
I want to convert word documents into images.
Each page in word document will be converted into images.
I found following example and it converts ppt file into image.
I found word to image convertor script in php but it is not working , I am getting no output after executing page.
I also tried phpword to convert word file to pdf and then get images by using imagick  but in the phpword i didn't get images(inside word file) data. i get only text in the coverted pdf file.
I tried so many ways but didn't get any solution.
Anyone can help me to found any way or solution?</p>

```<code>$word = new COM("word.application") or die("ERROR: Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}";
$word->Visible = 1;
$FilePath = "C:\\\\";
$DocFilename = "Sample.docx";
$stat = $word->Documents->Open(realpath("$DocFilename")) or die ("ERROR: Could not open Word Doc");
$word->Documents[1]->SaveAs("$FilePath", 17);
$word->Documents[1]->Close();
</code>```

答: Now i am using libreOffice on the live server for convert doc , docx , ppt , pptx to pdf and then use of imagick to get my images.</p>

Title: Convert doc and docx to images

Body:
I want to convert word documents into images.
Each page in word document will be converted into images.
I found following example and it converts ppt file into image.
I found word to image convertor script in php but it is not working , I am getting no output after executing page.
I also tried phpword to convert word file to pdf and then get images by using imagick  but in the phpword i didn't get images(inside word file) data. i get only text in the coverted pdf file.
I tried so many ways but didn't get any solution.
Anyone can help me to found any way or solution?

$word = new COM("word.application") or die("ERROR: Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}";
$word->Visible = 1;
$FilePath = "C:\\\\";
$DocFilename = "Sample.docx";
$stat = $word->Documents->Open(realpath("$DocFilename")) or die ("ERROR: Could not open Word Doc");
$word->Documents[1]->SaveAs("$FilePath", 17);
$word->Documents[1]->Close();


问:
Loop over columns of dataframe in R
How can I loop to perform the same test over columns with similar names in R?

for example I have three columns, named col30, col126, col145. I was thinking something like:

```<code>x <- c(30, 126, 145)

for (i in x) {

  wilcox.test(col(i) ~ level)

}
</code>```

is not working and provide the following error:

Error in eval(predvars, data, env) : attempt to apply non-function

答:
```<code>x <- c(30, 126, 145)
for (i in x) {
    wilcox.test(df[,i] ~ level)
}
</code>```

where df is your data frame.

Title: Loop over columns of dataframe in R

Body:
How can I loop to perform the same test over columns with similar names in R?

for example I have three columns, named col30, col126, col145. I was thinking something like:

x <- c(30, 126, 145)

for (i in x) {

  wilcox.test(col(i) ~ level)

}

is not working and provide the following error:

Error in eval(predvars, data, env) : attempt to apply non-function

Body:
x <- c(30, 126, 145)
for (i in x) {
    wilcox.test(df[,i] ~ level)
}

where df is your data frame.


问:
iOS: How to get speed and speed limit in Here map?
I am using here map SDK in my iOS project and want to show user current speed and speed limit in navigation.</p>

答:
speed limit from HERE:

https://route.cit.api.here.com/routing/7.2/calculateroute.json?waypoint0=52.295516,-1.979556&waypoint1=52.295516,-1.979556&legattributes=li&mode=fastest;car&app_code=your_app_code&app_id=your_app_id

A working example can be found on the

Get Route Information

https://developer.here.com/documentation/routing/dev_guide/topics/request-route-information.html


问:
Avoiding coupling with Strategy pattern
I am attempting to apply the Strategy pattern to a particular situation, but am having an issue with how to avoid coupling each concrete strategy to the context object providing data for it. The following is a simplified case of a pattern that occurs a few different ways, but should be handled in a similar way.

We have an object Acquisition that provides data relevant to a specific frame of time - basically a bunch of external data collected using different pieces of hardware. It's already too large because of the amount of data it contains, so I don't want to give it any further responsibility. We now need to take some of this data, and based on some configuration send a corresponding voltage to a piece of hardware.

So, imagine the following (much simplified) classes:

```<code>class Acquisition
{
    public Int32 IntegrationTime { get; set; }
    public Double Battery { get; set; }
    public Double Signal { get; set; }
}

interface IAnalogOutputter
{
    double getVoltage(Acquisition acq);
}

class BatteryAnalogOutputter : IAnalogOutputter
{
    double getVoltage(Acquisition acq)
    {
        return acq.Battery;
    }
}
</code>```

Now, every concrete strategy class has to be coupled to my Acquisition class, which is also one of the most likely classes to be modified since it's core to our application. This is still an improvement over the old design, which was a giant switch statement inside the Acquisition class. Each type of data may have a different conversion method (while Battery is a simple pass-through, others are not at all that simple), so I feel Strategy pattern or similar should be the way to go.

I will also note that in the final implementation, IAnalogOutputter would be an abstract class instead of an interface. These classes will be in a list that is configurable by the user and serialized to an XML file. The list must be editable at runtime and remembered, so Serializable must be part of our final solution. In case it makes a difference.

How can I ensure each implementation class gets the data it needs to work, without tying it to one of my most important classes? Or am I approaching this sort of problem in the completely wrong manner?

答:
Ok, I hate to not give someone else the credit here, but I found a hybrid solution that works very well for my purposes. It serializes perfectly, and greatly simplifies the addition of new output types. The key was a single interface, IOutputValueProvider. Also note how easily this pattern handles the retrieval of varying ways of storing the data (such as a Dictionary instead of a parameter).

```<code>interface IOutputValueProvider
{
    Double GetBattery();
    Double GetSignal();
    Int32 GetIntegrationTime();
    Double GetDictionaryValue(String key);
}

interface IAnalogOutputter
{
    double getVoltage(IOutputValueProvider provider);
}

class BatteryAnalogOutputter : IAnalogOutputter
{
    double getVoltage(IOutputValueProvider provider)
    {
        return provider.GetBattery();
    }
}

class DictionaryValueOutputter : IAnalogOutputter
{
    public String DictionaryKey { get; set; }
    public double getVoltage(IOutputValueProvider provider)
    {
        return provider.GetDictionaryValue(DictionaryKey);
    }
}
</code>```

So then, I just need to ensure Acquisition implements the interface:

```<code>class Acquisition : IOutputValueProvider
{
    public Int32 IntegrationTime { get; set; }
    public Double Battery { get; set; }
    public Double Signal { get; set; }
    public Dictionary<String, Double> DictionaryValues;

    public double GetBattery() { return Battery;}
    public double GetSignal() { return Signal; }
    public int GetIntegrationTime() { return IntegrationTime; }
    public double GetDictionaryValue(String key)
    {
        Double d = 0.0;
        return DictionaryValues.TryGetValue(key, out d) ? d : 0.0;
    }
}
</code>```

This isn't perfect, since now there's a gigantic interface that must be maintained and some duplicate code in Acquisition, but there's a heck of a lot less risk of something being changed affecting the other parts of my application. It also allows me to start subclassing Acquisition without having to change some of these external pieces. I hope this will help some others in similar situations.

Title: Avoiding coupling with Strategy pattern

Body:
I am attempting to apply the Strategy pattern to a particular situation, but am having an issue with how to avoid coupling each concrete strategy to the context object providing data for it. The following is a simplified case of a pattern that occurs a few different ways, but should be handled in a similar way.

We have an object Acquisition that provides data relevant to a specific frame of time - basically a bunch of external data collected using different pieces of hardware. It's already too large because of the amount of data it contains, so I don't want to give it any further responsibility. We now need to take some of this data, and based on some configuration send a corresponding voltage to a piece of hardware.

So, imagine the following (much simplified) classes:

class Acquisition
{
    public Int32 IntegrationTime { get; set; }
    public Double Battery { get; set; }
    public Double Signal { get; set; }
}

interface IAnalogOutputter
{
    double getVoltage(Acquisition acq);
}

class BatteryAnalogOutputter : IAnalogOutputter
{
    double getVoltage(Acquisition acq)
    {
        return acq.Battery;
    }
}

Now, every concrete strategy class has to be coupled to my Acquisition class, which is also one of the most likely classes to be modified since it's core to our application. This is still an improvement over the old design, which was a giant switch statement inside the Acquisition class. Each type of data may have a different conversion method (while Battery is a simple pass-through, others are not at all that simple), so I feel Strategy pattern or similar should be the way to go.

I will also note that in the final implementation, IAnalogOutputter would be an abstract class instead of an interface. These classes will be in a list that is configurable by the user and serialized to an XML file. The list must be editable at runtime and remembered, so Serializable must be part of our final solution. In case it makes a difference.

How can I ensure each implementation class gets the data it needs to work, without tying it to one of my most important classes? Or am I approaching this sort of problem in the completely wrong manner?

Body:
Ok, I hate to not give someone else the credit here, but I found a hybrid solution that works very well for my purposes. It serializes perfectly, and greatly simplifies the addition of new output types. The key was a single interface, IOutputValueProvider. Also note how easily this pattern handles the retrieval of varying ways of storing the data (such as a Dictionary instead of a parameter).

interface IOutputValueProvider
{
    Double GetBattery();
    Double GetSignal();
    Int32 GetIntegrationTime();
    Double GetDictionaryValue(String key);
}

interface IAnalogOutputter
{
    double getVoltage(IOutputValueProvider provider);
}

class BatteryAnalogOutputter : IAnalogOutputter
{
    double getVoltage(IOutputValueProvider provider)
    {
        return provider.GetBattery();
    }
}

class DictionaryValueOutputter : IAnalogOutputter
{
    public String DictionaryKey { get; set; }
    public double getVoltage(IOutputValueProvider provider)
    {
        return provider.GetDictionaryValue(DictionaryKey);
    }
}

So then, I just need to ensure Acquisition implements the interface:

class Acquisition : IOutputValueProvider
{
    public Int32 IntegrationTime { get; set; }
    public Double Battery { get; set; }
    public Double Signal { get; set; }
    public Dictionary<String, Double> DictionaryValues;

    public double GetBattery() { return Battery;}
    public double GetSignal() { return Signal; }
    public int GetIntegrationTime() { return IntegrationTime; }
    public double GetDictionaryValue(String key)
    {
        Double d = 0.0;
        return DictionaryValues.TryGetValue(key, out d) ? d : 0.0;
    }
}

This isn't perfect, since now there's a gigantic interface that must be maintained and some duplicate code in Acquisition, but there's a heck of a lot less risk of something being changed affecting the other parts of my application. It also allows me to start subclassing Acquisition without having to change some of these external pieces. I hope this will help some others in similar situations.


答:
There are no uid_program 's in kegiatan,change in order of joining tables may result the data for program column </p>

```<code>SELECT
  `mst_urusan`.`urusan`,
  `mst_program`.`program`,
  `mst_kegiatan`.`kegiatan`
FROM
  `mst_urusan`
  LEFT OUTER JOIN `mst_program` ON (`mst_program`.`uid_urusan` = `mst_urusan`.`uid_urusan`)
  LEFT OUTER JOIN `mst_kegiatan` ON (`mst_kegiatan`.`uid_program` = `mst_program`.`uid_program`)
</code>```

Title: Getting null when join 3 tables in mysql

Body:
so, here is my tables, i'd like to join 3 tables using JOIN query, but always getting null on some column,

mst_urusan
+------------+------------------------+
| uid_urusan | urusan                 |
+------------+------------------------+
|          1 | PANGAN                 |
|          2 | KELAUTAN DAN PERIKANAN |
|          3 | PERTANIAN              |
+------------+------------------------+

mst_program
+-------------+------------------------------------------------------------------------------+------------+
| uid_program | program                                                                      | uid_urusan |
+-------------+------------------------------------------------------------------------------+------------+
|          11 | Program Tata Kelola Pemerintahan                                             |          1 |
|          12 | Program Peningkatan Ketersediaan, Distribusi dan Penanganan Kerawanan Pangan |          1 |
|          13 | Program Peningkatan Keanekaragaman Konsumsi dan Keamanan Pangan              |          1 |
|          14 | Program Produktivitas Perikanan                                              |          2 |
|          15 | Program Produktivitas Pertanian dan Peternakan                               |          3 |
+-------------+------------------------------------------------------------------------------+------------+

mst_kegiatan
+--------------+-----------------------------------------------------------------------------+------------+-------------+
| uid_kegiatan | kegiatan                                                                    | uid_urusan | uid_program |
+--------------+-----------------------------------------------------------------------------+------------+-------------+
|            1 | Pelayanan Administrasi Perkantoran                                          |          1 |           1 |
|            2 | Peningkatan Sarana dan Prasarana Aparatur                                   |          1 |           1 |
|            3 | Peningkatan Kapasitas dan Pengelolaan Sumber Daya Aparatur Perangkat Daerah |          1 |           1 |
|            4 | Peningkatan Ketersediaan Pangan                                             |          1 |           2 |
|            5 | Koordinasi, Pemantauan dan Pemantapan Distribusi Pangan Daerah              |          1 |           2 |
|            6 | Penanganan Kerawanan Pangan                                                 |          1 |           3 |
|            7 | Diversifikasi Pengembangan Pangan                                           |          1 |           3 |
|            8 | Pengawasan Keamanan Pangan                                                  |          1 |           3 |
|            9 | Pembinaan dan Pengembangan Perikanan                                        |          2 |           4 |
|           10 | Produktivitas Pertanian Perkotaan                                           |          3 |           5 |
|           11 | Pembinaan Peternakan dan Kesehatan Hewan                                    |          3 |           5 |
|           12 | Pengembangan Pertanian dan Perikanan Terpadu                                |          3 |           5 |
+--------------+-----------------------------------------------------------------------------+------------+-------------+

i try using JOIN but i've got some null on column,

SELECT
  `mst_urusan`.`urusan`,
  `mst_program`.`program`,
  `mst_kegiatan`.`kegiatan`
FROM
  `mst_kegiatan`
  LEFT OUTER JOIN `mst_urusan` ON (`mst_kegiatan`.`uid_urusan` = `mst_urusan`.`uid_urusan`)
  LEFT OUTER JOIN `mst_program` ON (`mst_kegiatan`.`uid_program` = `mst_program`.`uid_program`)

the result is like this,

+------------------------+---------+-----------------------------------------------------------------------------+
| urusan                 | program | kegiatan                                                                    |
+------------------------+---------+-----------------------------------------------------------------------------+
| PANGAN                 | NULL    | Pelayanan Administrasi Perkantoran                                          |
| PANGAN                 | NULL    | Peningkatan Sarana dan Prasarana Aparatur                                   |
| PANGAN                 | NULL    | Peningkatan Kapasitas dan Pengelolaan Sumber Daya Aparatur Perangkat Daerah |
| PANGAN                 | NULL    | Peningkatan Ketersediaan Pangan                                             |
| PANGAN                 | NULL    | Koordinasi, Pemantauan dan Pemantapan Distribusi Pangan Daerah              |
| PANGAN                 | NULL    | Penanganan Kerawanan Pangan                                                 |
| PANGAN                 | NULL    | Diversifikasi Pengembangan Pangan                                           |
| PANGAN                 | NULL    | Pengawasan Keamanan Pangan                                                  |
| KELAUTAN DAN PERIKANAN | NULL    | Pembinaan dan Pengembangan Perikanan                                        |
| PERTANIAN              | NULL    | Produktivitas Pertanian Perkotaan                                           |
| PERTANIAN              | NULL    | Pembinaan Peternakan dan Kesehatan Hewan                                    |
| PERTANIAN              | NULL    | Pengembangan Pertanian dan Perikanan Terpadu                                |
+------------------------+---------+-----------------------------------------------------------------------------+

i'd like the result like picture bellow, any suggestion ?
 https://i.stack.imgur.com/jO1Tc.png

Body:
There are no uid_program 's in kegiatan,change in order of joining tables may result the data for program column

SELECT
  `mst_urusan`.`urusan`,
  `mst_program`.`program`,
  `mst_kegiatan`.`kegiatan`
FROM
  `mst_urusan`
  LEFT OUTER JOIN `mst_program` ON (`mst_program`.`uid_urusan` = `mst_urusan`.`uid_urusan`)
  LEFT OUTER JOIN `mst_kegiatan` ON (`mst_kegiatan`.`uid_program` = `mst_program`.`uid_program`)