问:
Keras shapes input for training and prediction raising value and attribute errors
I am having difficulty inputting data into a simple keras model for both predicting and training. I have looked at the related questions but after spending 6 hours attempting to figure this out on my own I am still struggling with this.

Imports and  network:

```<code>from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow import convert_to_tensor
from random import randint

model = keras.Sequential()
model.add(Dense(3, activation='relu', input_dim=5))
model.add(Dense(4, activation='sigmoid'))
model.add(Dense(2))
model.compile(loss=keras.losses.MeanSquaredError(),
              optimizer='adam',
              metrics=['MeanSquaredError'])
</code>```

Attempting to predict with the network:

```<code>X = [4, 5, 2, 8, 9]
tensor = convert_to_tensor(X)
print(tensor.shape) # Prints (5, ) as expected
prediction = model.predict(tensor)
</code>```

The following error is raised:

ValueError: Error when checking input: expected dense_input to have shape (5,) but got array with shape (1,)

Trying to train the network:

```<code>states = [[7, 8, 3, 9, 7], [0, 7, 5, 0, 3], [2, 5, 8, 1, 10], [9, 9, 9, 8, 6]]
actions = [[1, 0], [0, 1], [0, 1], [0, 1]]

tensor_states = convert_to_tensor(states)
tensor_actions = convert_to_tensor(actions)

print(tensor_states.shape)      # Prints (4, 5)
print(tensor_actions.shape)     # Prints (4, 2)

model.fit(tensor_states, tensor_actions, verbose=0)
</code>```

The following error is raised:

ValueError: TypeError: len() of unsized object

Without verbose=0 I get this error:

AttributeError: 'ProgbarLogger' object has no attribute 'log_values'

I am running in a conda environment.

I asked a previous question on this topic but I realized I overcomplicated the issue and was not exactly sure what I was asking. Now that I have done more research I feel I have boiled down my issue to the most basic form. I wrote this new question after consideration of this meta post. If I should have just edited my previous question please let me know.

EDIT - Trouble Shooting with darcycp

As the answer given below points out I should be giving a column to predict the network (using two sets of brackets). However, this gives the following error:

ValueError: TypeError: len() of unsized object

Then not using the tensor (as keras predict function can directly accept python lists) gives the following error:

ValueError: Attempt to convert a value (4) with an unsupported type () to a Tensor

Which is extremely unusual to me as I do not have numpy imported into this program.

答:
What I think is going on here is that your tensor X is a tensor of 5, 1-D inputs. When what you want it to be is a single tensor with one input, where a valid input for this model is made up of 5 numbers.

Try declaring instead as:

```<code>X =  [[4, 5, 2, 8, 9]]
</code>```

You can think of X as a array that can be full of different instances of inputs to your task. Each one of those instances is itself an array of inputs. While in this case X only has 1 input in another siutation it may look like:

```<code>X =  [[4, 5, 2, 8, 9],[6,7,9,2,5]]
</code>```

That is to say X is now a list of len() == 2, each item in that list is a input to your model. Keras layers by default assume that X will consist of batches of input data.

Body:
I am having difficulty inputting data into a simple keras model for both predicting and training. I have looked at the related questions but after spending 6 hours attempting to figure this out on my own I am still struggling with this.

Imports and  network:

from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow import convert_to_tensor
from random import randint

model = keras.Sequential()
model.add(Dense(3, activation='relu', input_dim=5))
model.add(Dense(4, activation='sigmoid'))
model.add(Dense(2))
model.compile(loss=keras.losses.MeanSquaredError(),
              optimizer='adam',
              metrics=['MeanSquaredError'])

Attempting to predict with the network:

X = [4, 5, 2, 8, 9]
tensor = convert_to_tensor(X)
print(tensor.shape) # Prints (5, ) as expected
prediction = model.predict(tensor)

The following error is raised:

ValueError: Error when checking input: expected dense_input to have shape (5,) but got array with shape (1,)

Trying to train the network:

states = [[7, 8, 3, 9, 7], [0, 7, 5, 0, 3], [2, 5, 8, 1, 10], [9, 9, 9, 8, 6]]
actions = [[1, 0], [0, 1], [0, 1], [0, 1]]

tensor_states = convert_to_tensor(states)
tensor_actions = convert_to_tensor(actions)

print(tensor_states.shape)      # Prints (4, 5)
print(tensor_actions.shape)     # Prints (4, 2)

model.fit(tensor_states, tensor_actions, verbose=0)

The following error is raised:

ValueError: TypeError: len() of unsized object

Without verbose=0 I get this error:

AttributeError: 'ProgbarLogger' object has no attribute 'log_values'

I am running in a conda environment.

I asked a previous question on this topic but I realized I overcomplicated the issue and was not exactly sure what I was asking. Now that I have done more research I feel I have boiled down my issue to the most basic form. I wrote this new question after consideration of this meta post. If I should have just edited my previous question please let me know.

EDIT - Trouble Shooting with darcycp

As the answer given below points out I should be giving a column to predict the network (using two sets of brackets). However, this gives the following error:

ValueError: TypeError: len() of unsized object

Then not using the tensor (as keras predict function can directly accept python lists) gives the following error:

ValueError: Attempt to convert a value (4) with an unsupported type () to a Tensor

Which is extremely unusual to me as I do not have numpy imported into this program.

Body:
What I think is going on here is that your tensor X is a tensor of 5, 1-D inputs. When what you want it to be is a single tensor with one input, where a valid input for this model is made up of 5 numbers.

Try declaring instead as:

X =  [[4, 5, 2, 8, 9]]

You can think of X as a array that can be full of different instances of inputs to your task. Each one of those instances is itself an array of inputs. While in this case X only has 1 input in another siutation it may look like:

X =  [[4, 5, 2, 8, 9],[6,7,9,2,5]]

That is to say X is now a list of len() == 2, each item in that list is a input to your model. Keras layers by default assume that X will consist of batches of input data.


来源: stackexchange

问:
How to do an OR with Objectify
I havent been able to figure out how to do something equivalent to this SQL statement in Objectify

SELECT * FROM myTable WHERE myTable.attribute = 'X' OR myTable.attribute = 'Y'.

Any help would be appreciated.

答:
You can't use 'OR' criteria in App Engine. Each query is executed as a single index scan, and that's not possible with disjunctions. Instead, you need to execute each query separately, and intersect the results.

I'm not sure how this relates to text search, however.

ContentLicense: CC BY-SA 3.0

Title: How to do an OR with Objectify


问:
How do I use numpy genfromtxt to read a fixed width, mixed format file?
A sample of my data file is below.  Note that I have not included all of the header. Note also that often a specific data value is left blank (in this case CALL for rows 1 and 5 but it can be other columns too).

```<code>USAF   WBAN  STATION NAME                  CTRY ST CALL  LAT     LON      ELEV(M) BEGIN    END
703165 99999 SAND POINT                    US   AK       +55.333 -160.500 +0006.0 19730107 20041231
703210 25513 DILLINGHAM AIRPORT            US   AK PADL  +59.050 -158.517 +0026.2 20060101 20200516
703210 99999 DILLINGHAM MUNI               US   AK PADL  +59.050 -158.517 +0029.0 19730101 20051231
703260 25503 KING SALMON AIRPORT           US   AK PAKN  +58.683 -156.656 +0020.4 19420110 20200516
703263 99999 KING SALMON                   US   AK       +58.683 -156.683 +0017.0 19801002 19960630
</code>```

I'd like to simply read each column in as a different 1 dimensional numpy array.  I've used the following code:

```<code>usaf, wban, name, ctry, st, call, lat3, lon3, elv, begin, end = \
  np.genfromtxt('./documentation/isd-history.txt', \
  dtype=('S6', 'S6', 'S30', 'S3', 'S5', 'S5', float, float, float, int, int), \
  comments='None', delimiter=[6, 6, 30, 3, 5, 5, 9, 9, 8, 9, 9 ],\
  skip_header=22, unpack=True)
</code>```

I get the following error

```<code>ValueError: too many values to unpack
</code>```

This seems like a pretty straightforward procedure but clearly I'm missing something.  Any advice is appreciated.

ContentLicense: CC BY-SA 4.0

Body:
A sample of my data file is below.  Note that I have not included all of the header. Note also that often a specific data value is left blank (in this case CALL for rows 1 and 5 but it can be other columns too).

USAF   WBAN  STATION NAME                  CTRY ST CALL  LAT     LON      ELEV(M) BEGIN    END
703165 99999 SAND POINT                    US   AK       +55.333 -160.500 +0006.0 19730107 20041231
703210 25513 DILLINGHAM AIRPORT            US   AK PADL  +59.050 -158.517 +0026.2 20060101 20200516
703210 99999 DILLINGHAM MUNI               US   AK PADL  +59.050 -158.517 +0029.0 19730101 20051231
703260 25503 KING SALMON AIRPORT           US   AK PAKN  +58.683 -156.656 +0020.4 19420110 20200516
703263 99999 KING SALMON                   US   AK       +58.683 -156.683 +0017.0 19801002 19960630

I'd like to simply read each column in as a different 1 dimensional numpy array.  I've used the following code:

usaf, wban, name, ctry, st, call, lat3, lon3, elv, begin, end = \
  np.genfromtxt('./documentation/isd-history.txt', \
  dtype=('S6', 'S6', 'S30', 'S3', 'S5', 'S5', float, float, float, int, int), \
  comments='None', delimiter=[6, 6, 30, 3, 5, 5, 9, 9, 8, 9, 9 ],\
  skip_header=22, unpack=True)

I get the following error

ValueError: too many values to unpack

This seems like a pretty straightforward procedure but clearly I'm missing something.  Any advice is appreciated.

Body:
Your sample with the delimiter does produce 11 fields:

In [83]: data = np.genfromtxt(txt.splitlines(),delimiter=[6, 6, 30, 3, 5, 5, 9, 9, 8, 9,
    ...: 9 ],names=True, dtype=None, encoding=None)
In [84]: data
Out[84]:
array([(703165, 99999, ' SAND POINT                   ', ' US', '   AK', '     ', 55.333, -160.5  ,  6. , 19730107, 20041231),
       (703210, 25513, ' DILLINGHAM AIRPORT           ', ' US', '   AK', ' PADL', 59.05 , -158.517, 26.2, 20060101, 20200516),
       (703210, 99999, ' DILLINGHAM MUNI              ', ' US', '   AK', ' PADL', 59.05 , -158.517, 29. , 19730101, 20051231),
       (703260, 25503, ' KING SALMON AIRPORT          ', ' US', '   AK', ' PAKN', 58.683, -156.656, 20.4, 19420110, 20200516),
       (703263, 99999, ' KING SALMON                  ', ' US', '   AK', '     ', 58.683, -156.683, 17. , 19801002, 19960630)],
      dtype=[('USAF', '<i8'), ('WBAN', '<i8'), ('STATION_NAME', '<U30'), ('CT', '<U3'), ('RY_ST', '<U5'), ('CALL', '<U5'), ('LAT', '<f8'), ('LON', '<f8'), ('ELEVM', '<f8'), ('BEGIN', '<i8'), ('END', '<i8')])

or with the rest of your command

In [93]: data=np.genfromtxt(txt.splitlines(), \
    ...:   dtype=('S6', 'S6', 'S30', 'S3', 'S5', 'S5', float, float, float, int, int), \
    ...:   comments='None', delimiter=[6, 6, 30, 3, 5, 5, 9, 9, 8, 9, 9 ],\
    ...:   skip_header=1
    ...: )
In [94]: data.dtype.fields
Out[94]:
mappingproxy({'f0': (dtype('S6'), 0),
              'f1': (dtype('S6'), 6),
              'f2': (dtype('S30'), 12),
              'f3': (dtype('S3'), 42),
              'f4': (dtype('S5'), 45),
              'f5': (dtype('S5'), 50),
              'f6': (dtype('float64'), 55),
              'f7': (dtype('float64'), 63),
              'f8': (dtype('float64'), 71),
              'f9': (dtype('int64'), 79),
              'f10': (dtype('int64'), 87)})

unpack=True doesn't change that.

unpack : bool, optional
    If True, the returned array is transposed, so that arguments may be
    unpacked using ``x, y, z = loadtxt(...)``

With compound dtype, fields, the array is 1d:

In [99]: data.shape
Out[99]: (5,)

and the transpose does nothing.  This unpacking only works if the dtype is simple, and result is a 2d array (e.g. (5,11), transpose to (11,5) and unpack to 11 variables.).  Unpacking should be clearer about that distinction.

You can unpack fields with individual assignment

In [100]: data['f0']
Out[100]: array([b'703165', b'703210', b'703210', b'703260', b'703263'], dtype='|S6')
In [101]: data['f2']
Out[101]:
array([b' SAND POINT                   ',
       b' DILLINGHAM AIRPORT           ',
       b' DILLINGHAM MUNI              ',
       b' KING SALMON AIRPORT          ',
       b' KING SALMON                  '], dtype='|S30')

In [102]: data.dtype.names
Out[102]: ('f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10')
In [103]: foo,bar,baz = [data[name] for name in data.dtype.names[:3]]
In [104]: bar
Out[104]: array([b' 99999', b' 25513', b' 99999', b' 25503', b' 99999'], dtype='|S6')


问:
Get Specific Data from Excel using Pandas and Convert Everything into a String as well as NaN
I have an excel file with the 1st row always empty.
The 2nd row with data I don't need.
The 3rd row is always a header and the following rows are always data with Total being under Title_3 and Title_4.

I read the files using pandas. I've attached the output of the result.

My goal is that I want everything in the array to be a string as well as nan. How can I replace the nan with a string and have the output display like this:

Goal Output

```<code>['nan', 'Title_1', 'RED_100', '2019-01-01 00:00:00', '10', 'nan']
['nan', 'Title_2', 'GREEN_200', '2018-02-02 00:00:00', '20', 'nan']
['nan', 'Title_3', 'RED_300', '2019-11-15 00:00:00', '30', 'Total']
['123456', 'Title_4', 'YELLOW_100', '2019-01-01 00:00:00', '40', '100']
</code>```

Code

```<code>import pandas as pd
import io
import numpy as np

path = r'C:\Temp Files\Excel_2.xlsx'

df = pd.read_excel(path, dtype=str, index_col=None, na_values=['NA'])

#df.drop(df.head(2).index, inplace=True)

print(df)
res = (df.dropna(how='all') #remove completely empty rows
.dropna(how='all',axis=1) #remove completely empty columns
.T #flip columns into row position
#convert to list
.to_numpy()
.tolist()
)

print()
Title_1 = res[1]
print(Title_1)
</code>```

Output

```<code>            Unnamed: 0           Unnamed: 1           Unnamed: 2           Unnamed: 3
0                  NaN                  NaN                  NaN               123456
1              Title_1              Title_2              Title_3              Title_4
2              RED_100            GREEN_200              RED_300           YELLOW_100
3  2019-01-01 00:00:00  2018-02-02 00:00:00  2019-11-15 00:00:00  2019-01-01 00:00:00
4                   10                   20                   30                   40
5                  NaN                  NaN                Total                  100

[nan, 'Title_2', 'GREEN_200', '2018-02-02 00:00:00', '20', nan]
</code>```

My Excel File

Data I Need

答:
```<code>#add skiprows=1, nrows=6
df = pd.read_excel(path, dtype=str, index_col=None, na_values=['NA'], skiprows=1, nrows=6)

#transpose the df
df_transposed = df.T

#transform all entries to strings (including nan)
df_transposed = df_transposed.applymap(str)
</code>```

You already put effort into providing info for the question but it would have been really helpful if you had also provided a test dataframe like this: df = pd.DataFrame(data=...
The Code is therefore untested!

Body:
I have an excel file with the 1st row always empty.
The 2nd row with data I don't need.
The 3rd row is always a header and the following rows are always data with Total being under Title_3 and Title_4.

I read the files using pandas. I've attached the output of the result.

My goal is that I want everything in the array to be a string as well as nan. How can I replace the nan with a string and have the output display like this:

Goal Output

['nan', 'Title_1', 'RED_100', '2019-01-01 00:00:00', '10', 'nan']
['nan', 'Title_2', 'GREEN_200', '2018-02-02 00:00:00', '20', 'nan']
['nan', 'Title_3', 'RED_300', '2019-11-15 00:00:00', '30', 'Total']
['123456', 'Title_4', 'YELLOW_100', '2019-01-01 00:00:00', '40', '100']

Code

import pandas as pd
import io
import numpy as np

path = r'C:\Temp Files\Excel_2.xlsx'

df = pd.read_excel(path, dtype=str, index_col=None, na_values=['NA'])

#df.drop(df.head(2).index, inplace=True)

print(df)
res = (df.dropna(how='all') #remove completely empty rows
.dropna(how='all',axis=1) #remove completely empty columns
.T #flip columns into row position
#convert to list
.to_numpy()
.tolist()
)

print()
Title_1 = res[1]
print(Title_1)

Output

            Unnamed: 0           Unnamed: 1           Unnamed: 2           Unnamed: 3
0                  NaN                  NaN                  NaN               123456
1              Title_1              Title_2              Title_3              Title_4
2              RED_100            GREEN_200              RED_300           YELLOW_100
3  2019-01-01 00:00:00  2018-02-02 00:00:00  2019-11-15 00:00:00  2019-01-01 00:00:00
4                   10                   20                   30                   40
5                  NaN                  NaN                Total                  100

[nan, 'Title_2', 'GREEN_200', '2018-02-02 00:00:00', '20', nan]

My Excel File

Data I Need

Body:
#add skiprows=1, nrows=6
df = pd.read_excel(path, dtype=str, index_col=None, na_values=['NA'], skiprows=1, nrows=6)

#transpose the df
df_transposed = df.T

#transform all entries to strings (including nan)
df_transposed = df_transposed.applymap(str)

You already put effort into providing info for the question but it would have been really helpful if you had also provided a test dataframe like this: df = pd.DataFrame(data=...
The Code is therefore untested!


问:
not able to print output to console window while running xunit tests
```<code>public class test2InAnotherProject
{
    private readonly ITestOutputHelper output;

    public test2InAnotherProject(ITestOutputHelper output)
    {
        this.output = output;
    }
    int Diff(int a, int b)
    {
        return (a - b);
    }
    int Div(int a, int b)
    {
        return (b / a);
    }

    [Fact]
    public void Test2()
    {
        int a = 2, b = 4;

        output.WriteLine("Test1: Project 2 in old library");
        int c = Diff(a, b);
        Assert.Equal(c, (a - b));
        output.WriteLine("Test1: Asssert done Project 2 in old library");
    }

    [Fact]
    public void Test3()
    {
        int a = 2, b = 4;

        output.WriteLine("Test2: Project 2 in old library");
        int c = Div(a, b);
        Assert.Equal(c, (float)((b / a)));
        output.WriteLine("Test2: Assert done Project 2 in old library");
    }
}
</code>```

trying to print those lines when test is run through command prompt by using the command

dotnet test --no-build

Tried Console.Writeline, after which i tried with Output.WriteLine.
Even when i run from Visual Studio am not able to get those lines printed in output window.

答:
Running dotnete test from within powershell console like package Manager console  or powershell console ISE, you can get ALL the Console.WriteLine output for Xunit project.

In powershel ISE, run this script:

```<code>cls
cd 'path/to/project/test/folder'
dotnet test
</code>```

Also any Console.WriteLine(..) in the source code is displayed in the PS console.

Body:
public class test2InAnotherProject
{
    private readonly ITestOutputHelper output;

    public test2InAnotherProject(ITestOutputHelper output)
    {
        this.output = output;
    }
    int Diff(int a, int b)
    {
        return (a - b);
    }
    int Div(int a, int b)
    {
        return (b / a);
    }

    [Fact]
    public void Test2()
    {
        int a = 2, b = 4;

        output.WriteLine("Test1: Project 2 in old library");
        int c = Diff(a, b);
        Assert.Equal(c, (a - b));
        output.WriteLine("Test1: Asssert done Project 2 in old library");
    }

    [Fact]
    public void Test3()
    {
        int a = 2, b = 4;

        output.WriteLine("Test2: Project 2 in old library");
        int c = Div(a, b);
        Assert.Equal(c, (float)((b / a)));
        output.WriteLine("Test2: Assert done Project 2 in old library");
    }
}

trying to print those lines when test is run through command prompt by using the command

dotnet test --no-build

Tried Console.Writeline, after which i tried with Output.WriteLine.
Even when i run from Visual Studio am not able to get those lines printed in output window.

Body:
Running dotnete test from within powershell console like package Manager console  or powershell console ISE, you can get ALL the Console.WriteLine output for Xunit project.

In powershel ISE, run this script:

cls
cd 'path/to/project/test/folder'
dotnet test

Also any Console.WriteLine(..) in the source code is displayed in the PS console.


问:
How to determine which eclipse plugins are contributing to menus and toolbars and stop them
I am creating an RCP app which uses a host of third-party plugins. Some of these plugins contribute menus, menu items, and toolbar buttons that I do not wish to display. How can I determine which plugins are contributing these menus, menu items, and toolbar buttons and how can I disable them from doing so?</p>

答:
Alt + Shift + F2

then click some menu.

You can know contributor and menu URI.

Alt + Shift + F1 : inspect current active part and selection.

Alt + Shift + F3 : inspector contributor of Widget or item.

You needs plugin-spy plugin in runtime.


问:
Pandas groupby concat ungrouped column into comma separated string
I have the following example df:

```<code>        col1     col2    col3   doc_no
     0     a        x       f        0
     1     a        x       f        1
     2     b        x       g        2
     3     b        y       g        3
     4     c        x       t        3
     5     c        y       t        4
     6     a        x       f        5
     7     d        x       t        5
     8     d        x       t        6
</code>```

I want to group by the first 3 columns (col1, col2, col3), concatenate the fourth column (doc_no) into a line of strings based on the groupings of the first 3 columns, as well as also generate a sorted count column of the 3 column grouping (count). Example desired output below (column order doesn't matter):

```<code>        col1     col2    col3   count      doc_no
     0     a        x       f       3     0, 1, 5
     1     d        x       t       2        5, 6
     2     b        x       g       1           2
     3     b        y       g       1           3
     4     c        x       t       1           3
     5     c        y       t       1           4
</code>```

How would I go about doing this? I used the below line to get just the grouping and the count:

```<code>grouped_df = df.groupby(['col1','col2','col3']).size().reset_index(name='count')\
    .sort_values(['count'], ascending=False).reset_index()
</code>```

But I'm not sure how to also get the concatenated doc_no column in the same code line.

答:
Another way

```<code>df2=df.groupby(['col1','col2','col3']).doc_no.agg(doc_no=('doc_no',list)).reset_index()
df2['doc_no']=df2['doc_no'].astype(str).str[1:-1]
</code>```

Body:
I have the following example df:

        col1     col2    col3   doc_no
     0     a        x       f        0
     1     a        x       f        1
     2     b        x       g        2
     3     b        y       g        3
     4     c        x       t        3
     5     c        y       t        4
     6     a        x       f        5
     7     d        x       t        5
     8     d        x       t        6

I want to group by the first 3 columns (col1, col2, col3), concatenate the fourth column (doc_no) into a line of strings based on the groupings of the first 3 columns, as well as also generate a sorted count column of the 3 column grouping (count). Example desired output below (column order doesn't matter):

        col1     col2    col3   count      doc_no
     0     a        x       f       3     0, 1, 5
     1     d        x       t       2        5, 6
     2     b        x       g       1           2
     3     b        y       g       1           3
     4     c        x       t       1           3
     5     c        y       t       1           4

How would I go about doing this? I used the below line to get just the grouping and the count:

grouped_df = df.groupby(['col1','col2','col3']).size().reset_index(name='count')\
    .sort_values(['count'], ascending=False).reset_index()

But I'm not sure how to also get the concatenated doc_no column in the same code line.

Body:
Another way

df2=df.groupby(['col1','col2','col3']).doc_no.agg(doc_no=('doc_no',list)).reset_index()
df2['doc_no']=df2['doc_no'].astype(str).str[1:-1]


问:
fill html with fdf data in javascript
I want to fill an html document using a fdf data string.

I have an regex that parses FDF Data (Form Data from a PDF)

```<code>\/T\(([^)]*)\)\/V[(\/<]([^>)]*)
</code>```

Debuggex Demo
Result Demo

I want to use this fdf Data to populate my html document by matching the id.

let regexp = "\/T\(([^)]*)\)\/V[(\/<]([^>)]*)";
let fdfdata = "'><</T(Talent_FW_1)/V(0)>><</T(Talent_FW_10)/V(4)>><</T(Talent_FW_11)/V(4)>><</T(Talent_FW_12)/V(0)>><</T(Talent_FW_13)/V(3)>><</T(Talent_FW_14)/V(5)>><</T(Talent_FW_15)/V(4)>><</T(Talent_FW_16)/V(2)>><</T(Talent_FW_17)/V(7)>><</T(Talent_FW_18)/V(0)>><</T(Talent_FW_19)/V(0)>>'";

let fdfarray = [...fdfdata.matchAll(regexp)];

console.log(fdfarray[0]);
// is undefine

for (i = 0; i < fdfarray.length; i++) {

document.getElementById("array[i][0]").innerTEXT =  array[i][1];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="Talent_FW_14">this should be the Value Five<p>
<p id="Talent_FW_15">this should be the Value Fours<p></code>```

Source for the code

it seems the regex is not working as I expect and the array stays empty.

答:
Your regex as stated is a string, not a regex. You also need to add the g (global) flag to the regex to fill an array using .matchAll(). Here is the fixed regex:

let regexp = /\/T\(([^)]*)\)\/V[(\/<]([^>)]*)/g;
let fdfdata = "'><</T(Talent_FW_1)/V(0)>><</T(Talent_FW_10)/V(4)>><</T(Talent_FW_11)/V(4)>><</T(Talent_FW_12)/V(0)>><</T(Talent_FW_13)/V(3)>><</T(Talent_FW_14)/V(5)>><</T(Talent_FW_15)/V(4)>><</T(Talent_FW_16)/V(2)>><</T(Talent_FW_17)/V(7)>><</T(Talent_FW_18)/V(0)>><</T(Talent_FW_19)/V(0)>>'";
let fdfarray = [...fdfdata.matchAll(regexp)];

console.log(JSON.stringify(fdfarray, null, ' '));```
</div>
</div>
</p>

<p>returns:</p>

```[
  [
    "/T(Talent_FW_1)/V(0",
    "Talent_FW_1",
    "0"
  ],
  [
    "/T(Talent_FW_10)/V(4",
    "Talent_FW_10",
    "4"
  ],
...snip...
  [
    "/T(Talent_FW_19)/V(0",
    "Talent_FW_19",
    "0"
  ]
]
```

Title: fill html with fdf data in javascript

Body:
I want to fill an html document using a fdf data string.

I have an regex that parses FDF Data (Form Data from a PDF)

\/T\(([^)]*)\)\/V[(\/<]([^>)]*)

Debuggex Demo
Result Demo

I want to use this fdf Data to populate my html document by matching the id.

let regexp = "\/T\(([^)]*)\)\/V[(\/<]([^>)]*)";
let fdfdata = "'><</T(Talent_FW_1)/V(0)>><</T(Talent_FW_10)/V(4)>><</T(Talent_FW_11)/V(4)>><</T(Talent_FW_12)/V(0)>><</T(Talent_FW_13)/V(3)>><</T(Talent_FW_14)/V(5)>><</T(Talent_FW_15)/V(4)>><</T(Talent_FW_16)/V(2)>><</T(Talent_FW_17)/V(7)>><</T(Talent_FW_18)/V(0)>><</T(Talent_FW_19)/V(0)>>'";

let fdfarray = [...fdfdata.matchAll(regexp)];

console.log(fdfarray[0]);
// is undefine

for (i = 0; i < fdfarray.length; i++) {

document.getElementById("array[i][0]").innerTEXT =  array[i][1];
}

this should be the Value Five

this should be the Value Fours

Source for the code

it seems the regex is not working as I expect and the array stays empty.

Body:
Your regex as stated is a string, not a regex. You also need to add the g (global) flag to the regex to fill an array using .matchAll(). Here is the fixed regex:

let regexp = /\/T\(([^)]*)\)\/V[(\/<]([^>)]*)/g;
let fdfdata = "'><</T(Talent_FW_1)/V(0)>><</T(Talent_FW_10)/V(4)>><</T(Talent_FW_11)/V(4)>><</T(Talent_FW_12)/V(0)>><</T(Talent_FW_13)/V(3)>><</T(Talent_FW_14)/V(5)>><</T(Talent_FW_15)/V(4)>><</T(Talent_FW_16)/V(2)>><</T(Talent_FW_17)/V(7)>><</T(Talent_FW_18)/V(0)>><</T(Talent_FW_19)/V(0)>>'";
let fdfarray = [...fdfdata.matchAll(regexp)];

console.log(JSON.stringify(fdfarray, null, ' '));

returns:

[
  [
    "/T(Talent_FW_1)/V(0",
    "Talent_FW_1",
    "0"
  ],
  [
    "/T(Talent_FW_10)/V(4",
    "Talent_FW_10",
    "4"
  ],
...snip...
  [
    "/T(Talent_FW_19)/V(0",
    "Talent_FW_19",
    "0"
  ]
]


问:
Why `std::i64::MIN..=-1i64` and `1i64..=std::i64::MAX` are not covered in my pattern?
How to match an i64 variable against pattern of positive, zero and negative?

Say I have the following function f1, I would like to do a match, return -1 for negative input, 1 for positive input, 0 for 0.

```<code>fn f1(value: i64) -> i64 {
    match value {
        num if num > 0 => 1,
        0 => 0,
        num if num < 0 => -1,
    }
}

#[test]
fn test_f1() {
    assert_eq!(f1(-5), -1);
}
</code>```

The Playground link is here

But it complains "error[E0004]: non-exhaustive patterns: std::i64::MIN..=-1i64 and 1i64..=std::i64::MAX not covered". What's the correct pattern?

Feel free to suggest better ways to write the pattern, I hope to write it in range like:

```<code>fn f1(value: i64) -> i64 {
    match value {
        1.. => 1,
        0 => 0,
        ..=-1 => -1,
    }
}
</code>```

But even if I enable nightly, it still suggest "add #![feature(exclusive_range_pattern)] to the crate attributes to enable", which I am not sure how to do in Playground.

答:
If your goal is to write f1 as simply as possible, there's already a function for it, and it's called i64::signum:

```<code>fn sign(x: i64) {
    println!("sign of {} is {}", x, x.signum());
}

fn main() {
    sign(-10);
    sign(0);
    sign(10);
}
</code>```

If your goal is to write the sign comparison more generically to do something else, I'd write it like this:

```<code>fn sign(x: i64) {
    match x.signum() {
        -1 => println!("negative"),
        0 => println!("zero"),
        1 => println!("positive"),
        _ => unreachable!(),
    }
}
</code>```

The compiler can often optimize this code reasonably well.

Body:
How to match an i64 variable against pattern of positive, zero and negative?

Say I have the following function f1, I would like to do a match, return -1 for negative input, 1 for positive input, 0 for 0.

fn f1(value: i64) -> i64 {
    match value {
        num if num > 0 => 1,
        0 => 0,
        num if num < 0 => -1,
    }
}

#[test]
fn test_f1() {
    assert_eq!(f1(-5), -1);
}

The Playground link is here

But it complains "error[E0004]: non-exhaustive patterns: std::i64::MIN..=-1i64 and 1i64..=std::i64::MAX not covered". What's the correct pattern?

Feel free to suggest better ways to write the pattern, I hope to write it in range like:

fn f1(value: i64) -> i64 {
    match value {
        1.. => 1,
        0 => 0,
        ..=-1 => -1,
    }
}

But even if I enable nightly, it still suggest "add #![feature(exclusive_range_pattern)] to the crate attributes to enable", which I am not sure how to do in Playground.

Body:
If your goal is to write f1 as simply as possible, there's already a function for it, and it's called i64::signum:

fn sign(x: i64) {
    println!("sign of {} is {}", x, x.signum());
}

fn main() {
    sign(-10);
    sign(0);
    sign(10);
}

If your goal is to write the sign comparison more generically to do something else, I'd write it like this:

fn sign(x: i64) {
    match x.signum() {
        -1 => println!("negative"),
        0 => println!("zero"),
        1 => println!("positive"),
        _ => unreachable!(),
    }
}

The compiler can often optimize this code reasonably well.


答:
For plain patterns, rust can check whether the match arms are exhaustive. This is because plain patterns have a small number of forms, all of which rust has been told how to understand.

But your match arms involve if conditions, sometimes called guards in this context. The condition in a guard can have an arbitrary form. Some will look easy to you, but others are hard. No compiler, including rust's, will ever be able to predict arbitrary conditions. It's a mathematical fact. So rust does not waste its time trying.

In this particular case, there is actually a way to replace the guard with a plain pattern, which rust can check exhaustively.

```<code>fn f1(value: i64) -> i64 {
    match value {
        1..=std::i64::MAX => 1,
        0 => 0,
        std::i64::MIN..=-1 => -1,
    }
}
</code>```

You could use half-open ranges, but they require unstable rust.

```<code>fn f1(value: i64) -> i64 {
    match value {
        1.. => 1,
        0 => 0,
        ..=-1 => -1,
    }
}
</code>```

Title: Why `std::i64::MIN..=-1i64` and `1i64..=std::i64::MAX` are not covered in my pattern?

Body:
For plain patterns, rust can check whether the match arms are exhaustive. This is because plain patterns have a small number of forms, all of which rust has been told how to understand.

But your match arms involve if conditions, sometimes called guards in this context. The condition in a guard can have an arbitrary form. Some will look easy to you, but others are hard. No compiler, including rust's, will ever be able to predict arbitrary conditions. It's a mathematical fact. So rust does not waste its time trying.

In this particular case, there is actually a way to replace the guard with a plain pattern, which rust can check exhaustively.

fn f1(value: i64) -> i64 {
    match value {
        1..=std::i64::MAX => 1,
        0 => 0,
        std::i64::MIN..=-1 => -1,
    }
}

You could use half-open ranges, but they require unstable rust.

fn f1(value: i64) -> i64 {
    match value {
        1.. => 1,
        0 => 0,
        ..=-1 => -1,
    }
}


问:
Contain .jq Filter Results Into a Single Array
With the following input example:

```<code>{"contacts":{"orgid":"1","email":"janedoe@aol.com","first_name":"Jane","last_name":"Doe","phone":"4045551212","tags":["tag1","tag2"],"fields":[{"id":"2","value":"IB4220"},{"id":"3","value":"1994-05-18"},{"id":"12","value":"CONSULTANT"},{"id":"13","value":"janedoe@aol.com"},{"id":"6","value":"111 Main Blvd"},{"id":"7","value":"Babylon"},{"id":"8","value":"NY"},{"id":"9","value":"11702-1522"},{"id":"10","value":"US"},{"id":"11","value":""},{"id":"5","value":"http://www.something.com/janedoe"}]}}
{"contacts":{"orgid":"1","email":"janedoe@aol.com","first_name":"Jane","last_name":"Doe","phone":"4045551212","tags":["tag1","tag2"],"fields":[{"id":"2","value":"IB4220"},{"id":"3","value":"1994-05-18"},{"id":"12","value":"CONSULTANT"},{"id":"13","value":"janedoe@aol.com"},{"id":"6","value":"111 Main Blvd"},{"id":"7","value":"Babylon"},{"id":"8","value":"NY"},{"id":"9","value":"11702-1522"},{"id":"10","value":"US"},{"id":"11","value":""},{"id":"5","value":"http://www.something.com/janedoe"}]}}
</code>```

I am trying to contain my filter result in a single "contacts" array.

Here is my jq filter I am working with to no avail...

```<code>jq --slurp '.[] | .[].fields[].id |= tonumber | .[].orgid |= tonumber | {contacts: [.[]| {orgid: .["orgid"],email: .["email"],first_name: .["first_name"],last_name: .["last_name"],phone: .["phone"],tags:[ .["tags"]],fields}]}'
</code>```

It wraps each input line in a "contacts" array like follows...

```<code>{
  "contacts": [
    {
      "orgid": 1,
      "email": "janedoe@aol.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "phone": "4045551212",
      "tags": [
        [
          "tag1",
          "tag2"
        ]
      ],
      "fields": [
        {
          "id": 2,
          "value": "IB4220"
        },
        {
          "id": 3,
          "value": "1994-05-18"
        },
        {
          "id": 12,
          "value": "CONSULTANT"
        },
        {
          "id": 13,
          "value": "janedoe@aol.com"
        },
        {
          "id": 6,
          "value": "111 Main Blvd"
        },
        {
          "id": 7,
          "value": "Babylon"
        },
        {
          "id": 8,
          "value": "NY"
        },
        {
          "id": 9,
          "value": "11702-1522"
        },
        {
          "id": 10,
          "value": "US"
        },
        {
          "id": 11,
          "value": ""
        },
        {
          "id": 5,
          "value": "http://www.something.com/janedoe"
        }
      ]
    }
  ]
}
{
  "contacts": [
    {
      "orgid": 1,
      "email": "janedoe@aol.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "phone": "4045551212",
      "tags": [
        [
          "tag1",
          "tag2"
        ]
      ],
      "fields": [
        {
          "id": 2,
          "value": "IB4220"
        },
        {
          "id": 3,
          "value": "1994-05-18"
        },
        {
          "id": 12,
          "value": "CONSULTANT"
        },
        {
          "id": 13,
          "value": "janedoe@aol.com"
        },
        {
          "id": 6,
          "value": "111 Main Blvd"
        },
        {
          "id": 7,
          "value": "Babylon"
        },
        {
          "id": 8,
          "value": "NY"
        },
        {
          "id": 9,
          "value": "11702-1522"
        },
        {
          "id": 10,
          "value": "US"
        },
        {
          "id": 11,
          "value": ""
        },
        {
          "id": 5,
          "value": "http://www.something.com/janedoe"
        }
      ]
    }
  ]
}
</code>```

... But I need it like this (1 "contacts" array containing all the filtered input lines)...

```<code>{
    "contacts": [
        {
            "orgid": "1",
            "email": "janedoe@aol.com",
            "first_name": "Jane",
            "last_name": "Doe",
            "phone": "4045551212",
            "tags": [
                "tag1",
                "tag2"
            ],
            "fields": [
                {
                    "id": "2",
                    "value": "IB4220"
                },
                {
                    "id": "3",
                    "value": "1994-05-18"
                },
                {
                    "id": "12",
                    "value": "CONSULTANT"
                },
                {
                    "id": "13",
                    "value": "janedoe@aol.com"
                },
                {
                    "id": "6",
                    "value": "111 Main Blvd"
                },
                {
                    "id": "7",
                    "value": "Babylon"
                },
                {
                    "id": "8",
                    "value": "NY"
                },
                {
                    "id": "9",
                    "value": "11702-1522"
                },
                {
                    "id": "10",
                    "value": "US"
                },
                {
                    "id": "11",
                    "value": ""
                },
                {
                    "id": "5",
                    "value": "http://www.something.com/janedoe"
                }
            ]
        },
        {
            "orgid": "1",
            "email": "janedoe@aol.com",
            "first_name": "Jane",
            "last_name": "Doe",
            "phone": "4045551212",
            "tags": [
                "tag1",
                "tag2"
            ],
            "fields": [
                {
                    "id": "2",
                    "value": "IB4220"
                },
                {
                    "id": "3",
                    "value": "1994-05-18"
                },
                {
                    "id": "12",
                    "value": "CONSULTANT"
                },
                {
                    "id": "13",
                    "value": "janedoe@aol.com"
                },
                {
                    "id": "6",
                    "value": "111 Main Blvd"
                },
                {
                    "id": "7",
                    "value": "Babylon"
                },
                {
                    "id": "8",
                    "value": "NY"
                },
                {
                    "id": "9",
                    "value": "11702-1522"
                },
                {
                    "id": "10",
                    "value": "US"
                },
                {
                    "id": "11",
                    "value": ""
                },
                {
                    "id": "5",
                    "value": "http://www.something.com/janedoe"
                }
            ]
        }
    ]
}
</code>```

答:
To get the "expected" output as shown, you could use the following jq filter in conjunction with the -s option:

```<code>{ contacts: [.[] | [.contacts]] | add }
</code>```

However, your jq program indicates you also want to convert some strings to numbers.  That is q.e.d. along the lines you suggest and is thus left as an exercise, but a complete solution using an alternative approach is shown below.

Avoiding --slurp

In general, it's better to use -n with inputs:

```<code>[ [inputs.contacts
   | .fields[].id |= tonumber
   | .orgid |= tonumber] ]
| {contacts: add}

</code>```

Body:
With the following input example:

{"contacts":{"orgid":"1","email":"janedoe@aol.com","first_name":"Jane","last_name":"Doe","phone":"4045551212","tags":["tag1","tag2"],"fields":[{"id":"2","value":"IB4220"},{"id":"3","value":"1994-05-18"},{"id":"12","value":"CONSULTANT"},{"id":"13","value":"janedoe@aol.com"},{"id":"6","value":"111 Main Blvd"},{"id":"7","value":"Babylon"},{"id":"8","value":"NY"},{"id":"9","value":"11702-1522"},{"id":"10","value":"US"},{"id":"11","value":""},{"id":"5","value":"http://www.something.com/janedoe"}]}}
{"contacts":{"orgid":"1","email":"janedoe@aol.com","first_name":"Jane","last_name":"Doe","phone":"4045551212","tags":["tag1","tag2"],"fields":[{"id":"2","value":"IB4220"},{"id":"3","value":"1994-05-18"},{"id":"12","value":"CONSULTANT"},{"id":"13","value":"janedoe@aol.com"},{"id":"6","value":"111 Main Blvd"},{"id":"7","value":"Babylon"},{"id":"8","value":"NY"},{"id":"9","value":"11702-1522"},{"id":"10","value":"US"},{"id":"11","value":""},{"id":"5","value":"http://www.something.com/janedoe"}]}}

I am trying to contain my filter result in a single "contacts" array.

Here is my jq filter I am working with to no avail...

jq --slurp '.[] | .[].fields[].id |= tonumber | .[].orgid |= tonumber | {contacts: [.[]| {orgid: .["orgid"],email: .["email"],first_name: .["first_name"],last_name: .["last_name"],phone: .["phone"],tags:[ .["tags"]],fields}]}'

It wraps each input line in a "contacts" array like follows...

{
  "contacts": [
    {
      "orgid": 1,
      "email": "janedoe@aol.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "phone": "4045551212",
      "tags": [
        [
          "tag1",
          "tag2"
        ]
      ],
      "fields": [
        {
          "id": 2,
          "value": "IB4220"
        },
        {
          "id": 3,
          "value": "1994-05-18"
        },
        {
          "id": 12,
          "value": "CONSULTANT"
        },
        {
          "id": 13,
          "value": "janedoe@aol.com"
        },
        {
          "id": 6,
          "value": "111 Main Blvd"
        },
        {
          "id": 7,
          "value": "Babylon"
        },
        {
          "id": 8,
          "value": "NY"
        },
        {
          "id": 9,
          "value": "11702-1522"
        },
        {
          "id": 10,
          "value": "US"
        },
        {
          "id": 11,
          "value": ""
        },
        {
          "id": 5,
          "value": "http://www.something.com/janedoe"
        }
      ]
    }
  ]
}
{
  "contacts": [
    {
      "orgid": 1,
      "email": "janedoe@aol.com",
      "first_name": "Jane",
      "last_name": "Doe",
      "phone": "4045551212",
      "tags": [
        [
          "tag1",
          "tag2"
        ]
      ],
      "fields": [
        {
          "id": 2,
          "value": "IB4220"
        },
        {
          "id": 3,
          "value": "1994-05-18"
        },
        {
          "id": 12,
          "value": "CONSULTANT"
        },
        {
          "id": 13,
          "value": "janedoe@aol.com"
        },
        {
          "id": 6,
          "value": "111 Main Blvd"
        },
        {
          "id": 7,
          "value": "Babylon"
        },
        {
          "id": 8,
          "value": "NY"
        },
        {
          "id": 9,
          "value": "11702-1522"
        },
        {
          "id": 10,
          "value": "US"
        },
        {
          "id": 11,
          "value": ""
        },
        {
          "id": 5,
          "value": "http://www.something.com/janedoe"
        }
      ]
    }
  ]
}

... But I need it like this (1 "contacts" array containing all the filtered input lines)...

{
    "contacts": [
        {
            "orgid": "1",
            "email": "janedoe@aol.com",
            "first_name": "Jane",
            "last_name": "Doe",
            "phone": "4045551212",
            "tags": [
                "tag1",
                "tag2"
            ],
            "fields": [
                {
                    "id": "2",
                    "value": "IB4220"
                },
                {
                    "id": "3",
                    "value": "1994-05-18"
                },
                {
                    "id": "12",
                    "value": "CONSULTANT"
                },
                {
                    "id": "13",
                    "value": "janedoe@aol.com"
                },
                {
                    "id": "6",
                    "value": "111 Main Blvd"
                },
                {
                    "id": "7",
                    "value": "Babylon"
                },
                {
                    "id": "8",
                    "value": "NY"
                },
                {
                    "id": "9",
                    "value": "11702-1522"
                },
                {
                    "id": "10",
                    "value": "US"
                },
                {
                    "id": "11",
                    "value": ""
                },
                {
                    "id": "5",
                    "value": "http://www.something.com/janedoe"
                }
            ]
        },
        {
            "orgid": "1",
            "email": "janedoe@aol.com",
            "first_name": "Jane",
            "last_name": "Doe",
            "phone": "4045551212",
            "tags": [
                "tag1",
                "tag2"
            ],
            "fields": [
                {
                    "id": "2",
                    "value": "IB4220"
                },
                {
                    "id": "3",
                    "value": "1994-05-18"
                },
                {
                    "id": "12",
                    "value": "CONSULTANT"
                },
                {
                    "id": "13",
                    "value": "janedoe@aol.com"
                },
                {
                    "id": "6",
                    "value": "111 Main Blvd"
                },
                {
                    "id": "7",
                    "value": "Babylon"
                },
                {
                    "id": "8",
                    "value": "NY"
                },
                {
                    "id": "9",
                    "value": "11702-1522"
                },
                {
                    "id": "10",
                    "value": "US"
                },
                {
                    "id": "11",
                    "value": ""
                },
                {
                    "id": "5",
                    "value": "http://www.something.com/janedoe"
                }
            ]
        }
    ]
}

Body:
To get the "expected" output as shown, you could use the following jq filter in conjunction with the -s option:

{ contacts: [.[] | [.contacts]] | add }

However, your jq program indicates you also want to convert some strings to numbers.  That is q.e.d. along the lines you suggest and is thus left as an exercise, but a complete solution using an alternative approach is shown below.

Avoiding --slurp

In general, it's better to use -n with inputs:

[ [inputs.contacts
   | .fields[].id |= tonumber
   | .orgid |= tonumber] ]
| {contacts: add}


问:
nuxtjs/proxy url axios after dist
when I ty yarn dev In server rendering Proxy is working fine. fetching data from API site api.server.com/api

But after yarn generate axios request is calling self server

current.example.com/api.

Why it is not working in dist html?
Is Proxy working only in server side? Please, help.

I have NuxtJS config:

```<code>/*
 ** Nuxt.js modules
   */
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  axios: {
    proxy: true // Can be also an object with default options
  },

  proxy: {
    '/api/': {
      target: 'http://api.server.com/api',
      pathRewrite: {'^/api/': ''}
    },
    changeOrigin: true
  },
</code>```

plugins axios.js

```<code>import axios from 'axios'

export default axios.create({
  baseURL: '/api/',
  responseType: 'json'
})
</code>```

here I called that API like below index.vue

```<code><script>
import axios from '~/plugins/axios'

export default {
   mounted() {
    this.loaded();
  },
  methods: {
    loaded(){
        const location =  axios.get('/contact/contact_session.php').then((response) => {
          console.log(response);
        }).catch((err) => {
        });
    },
  }
}
</script>
</code>```

答: The proxy.js module only works in the development environment, in the production environment you must configure your web-server, preferably nginx, the proxy that takes your requests for example from the path "/ api / ..." and redirects it to the server you need.</p>

Title: nuxtjs/proxy url axios after dist

Body:
when I ty yarn dev In server rendering Proxy is working fine. fetching data from API site api.server.com/api

But after yarn generate axios request is calling self server

current.example.com/api.

Why it is not working in dist html?
Is Proxy working only in server side? Please, help.

I have NuxtJS config:

/*
 ** Nuxt.js modules
   */
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  axios: {
    proxy: true // Can be also an object with default options
  },

  proxy: {
    '/api/': {
      target: 'http://api.server.com/api',
      pathRewrite: {'^/api/': ''}
    },
    changeOrigin: true
  },

plugins axios.js

import axios from 'axios'

export default axios.create({
  baseURL: '/api/',
  responseType: 'json'
})

here I called that API like below index.vue


问:
Roblox Lua: I can't do arithmetic in the middle of print()
I am trying to put Rich as a variable, in the middle of print("You are" + print(Rich + 1) + "Rich"). It's inside a function so that whenever the player makes a part, which is going to be money in this case, their richness goes up by one:

```<code>    function createPart()
        local Rich = 0
        local myPart = Instance.new("Part")
        print("You are" + print(Rich + 1) + "Rich")
        myPart.Transparency = 0.5
        myPart. Anchored = true
        myPart.Position = Vector3.new(0,0,0)
        myPart.CanCollide = true
        myPart.Name = "lol" -- how to name a part after instance.new
        myPart.Parent = game.Workspace
    end
    createPart()
</code>```

I am stuck with that. Could I get an explanation as to how it would work?

答:
You're very close to your own solution. There are just a couple of mistakes in your attempt. The first is that you need a way to track the player's 'Richness'.

If you want this to appear in the Leaderboard at the top right, you need to attach a 'leaderstats' Value to the player. You can do this by doing the following:

```<code>-- somewhere in code, connect to the PlayerAdded event.
game.Players.PlayerAdded:Connect(function(player)
    -- in here, add a folder named 'leaderstats' to the Player.
    -- IMPORTANT: It must be named 'leaderstats' exactly, all lowercase
    local leaderstats = Instance.new('Folder')
    leaderstats.Name = 'leaderstats'

    -- then add the Richness to the added Player. Name if whatever you'd like
    local richness = Instance.new('IntValue')
    richness.Name = 'Richness'
    richness.Value = 0

    -- Parent this Richness value to the leaderstats to make it appear
    -- in the Leaderboard at the top right
    richness.Parent = leaderstats

    -- After you've created this Leaderboard stat, you need to
    -- parent the leaderstats to the Player
    leaderstats.Parent = player
end)
</code>```

Now all players will show up on the Leaderboard with a 'Richness' stat. They'll all be 0 until you update this value. You can update the value using RemoteEvents from the Client to the Server.

The Second is that you are printing to the Output window incorrectly. When you merge strings together (called concatenation), in Lua you do so by using '..'. For example:

```<code>print('Here is a ' .. 'part of a ' .. 'string')
</code>```

This will output the following in the 'Output' window:

```<code>Here is a part of a string
</code>```

So to put that into use in your code, you'd type the following:

```<code>print('You are ' .. (Rich + 1) .. ' Rich')
</code>```

Body:
I am trying to put Rich as a variable, in the middle of print("You are" + print(Rich + 1) + "Rich"). It's inside a function so that whenever the player makes a part, which is going to be money in this case, their richness goes up by one:

    function createPart()
        local Rich = 0
        local myPart = Instance.new("Part")
        print("You are" + print(Rich + 1) + "Rich")
        myPart.Transparency = 0.5
        myPart. Anchored = true
        myPart.Position = Vector3.new(0,0,0)
        myPart.CanCollide = true
        myPart.Name = "lol" -- how to name a part after instance.new
        myPart.Parent = game.Workspace
    end
    createPart()

I am stuck with that. Could I get an explanation as to how it would work?

Body:
You're very close to your own solution. There are just a couple of mistakes in your attempt. The first is that you need a way to track the player's 'Richness'.

If you want this to appear in the Leaderboard at the top right, you need to attach a 'leaderstats' Value to the player. You can do this by doing the following:

-- somewhere in code, connect to the PlayerAdded event.
game.Players.PlayerAdded:Connect(function(player)
    -- in here, add a folder named 'leaderstats' to the Player.
    -- IMPORTANT: It must be named 'leaderstats' exactly, all lowercase
    local leaderstats = Instance.new('Folder')
    leaderstats.Name = 'leaderstats'

    -- then add the Richness to the added Player. Name if whatever you'd like
    local richness = Instance.new('IntValue')
    richness.Name = 'Richness'
    richness.Value = 0

    -- Parent this Richness value to the leaderstats to make it appear
    -- in the Leaderboard at the top right
    richness.Parent = leaderstats

    -- After you've created this Leaderboard stat, you need to
    -- parent the leaderstats to the Player
    leaderstats.Parent = player
end)

Now all players will show up on the Leaderboard with a 'Richness' stat. They'll all be 0 until you update this value. You can update the value using RemoteEvents from the Client to the Server.

The Second is that you are printing to the Output window incorrectly. When you merge strings together (called concatenation), in Lua you do so by using '..'. For example:

print('Here is a ' .. 'part of a ' .. 'string')

This will output the following in the 'Output' window:

Here is a part of a string

So to put that into use in your code, you'd type the following:

print('You are ' .. (Rich + 1) .. ' Rich')


问:
How create a DefaultTableModel with data from text file
I have this test file text_file
My table view is enter image description here
I want suit each row with each column(first_row-first_column,second_row-second_column, etc..) Where is error?

```<code>        BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
</code>```

答:
```<code>    public class SimpleBookList {

    private ArrayList<SimpleBook> bookList;

    public SimpleBookList() {
        bookList = new ArrayList<SimpleBook>();
    }

    public void add(SimpleBook sb) {
        bookList.add(sb);
    }

    public ArrayList<SimpleBook> getBooks() {
        return bookList;
    }

    public void readFromTxt(String filename) {
        File file = new File(filename);
        FileReader reader = null;
        try {
            reader = new FileReader(file);
        } catch (FileNotFoundException e) {
            System.exit(1);
        }
        BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;
                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
</code>```

Body:
I have this test file text_file
My table view is enter image description here
I want suit each row with each column(first_row-first_column,second_row-second_column, etc..) Where is error?

        BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}


问:
What does make a URI derefenceable?
I found a very little information on this matter. What is the difference between dereferenceable and non-dereferenceable URIs? What does it mean to dereference a URI? How does the URI change after it has been derefenced?

When reading about linked data at Wikipedia, it is said:

Use HTTP URIs so that these things can be looked up (interpreted, "dereferenced").

This makes it sound like every individual that can be found with the HTTP URI, eg "can be looked up" can be dereferenced? But not all URIs are derefenceable.

答:
The simple answer is that if you can fetch a resource behind a URI by using exactly that URI, that URI is dereferenceable. This formulation means that only URLs are (potentially) dereferenceable and URNs aren't.

An extended definition is that all URIs you can map to a resource can be considered dereferenceable. For example, if you can map the URN urn:isbn:0451450523 to a book resource, then you may stretch the definition of dereferenceable URIs to include such URN (I wouldn't).

While on the topic, I think it's far better to mint URNs when your Linked Data resources are not dereferenceable (e.g. using an OBDA tool like Ontop) as to not confuse the consumers.

If you are looking at a quick way to make Linked Data resources dereferenceable, you can look at http://wifo5-03.informatik.uni-mannheim.de/pubby/

Title: What does make a URI derefenceable?


问:
Storing an HTML node as key in an *object*
Similar to this SO question, I would like to use HTML nodes as keys in an object (not an array).

Example:

```<code>var _hotspots = {
                 [object HTMLDivElement] : { someProps:[1,2,3] },
                 [object HTMLDivElement] : { someProps:[1,2,3] }
                }
</code>```

and so I might achieve things like this:

```<code>for( var a in _hotspots ){
    if(YAHOO.lang.hasOwnProperty(_hotspots, a)){
    alert('key nodeName: '+a.nodeName);
    }
}
</code>```

So far, when I alert out 'a' above, it alerts out that it is in fact a [object HTMLDivElement], so it all seemed fine - but I can't access properties on 'a', like nodeName.

Is what I am doing possible? Is it wrong? If I should be able to access properties on the object's key reference then please let me know and I'll write up a sample page.

cheers.

答: The keys of JavaScript objects are always character.  You could store the id as the key and then retreive the element in your function.</p>

Body:
Similar to this SO question, I would like to use HTML nodes as keys in an object (not an array).

Example:

var _hotspots = {
                 [object HTMLDivElement] : { someProps:[1,2,3] },
                 [object HTMLDivElement] : { someProps:[1,2,3] }
                }

and so I might achieve things like this:

for( var a in _hotspots ){
    if(YAHOO.lang.hasOwnProperty(_hotspots, a)){
    alert('key nodeName: '+a.nodeName);
    }
}

So far, when I alert out 'a' above, it alerts out that it is in fact a [object HTMLDivElement], so it all seemed fine - but I can't access properties on 'a', like nodeName.

Is what I am doing possible? Is it wrong? If I should be able to access properties on the object's key reference then please let me know and I'll write up a sample page.

cheers.


问:
Convert string with many dates to datetime
If my string consisted of just one date I'd use this:

```<code>datetime.datetime.strptime(string, '%b %d %Y').strftime('%Y-%m-%d')
</code>```

But since there are many along the string, I don't know how to proceed. How could I read the string and make the changes only where needed?

So here is my string:

```<code>s = 'Mar 27 2000*56.75*58.39*Mar 26 2000*53.10*56.13*Mar 25 2000*51.50*52.00'
</code>```

and what I expect right after:

```<code>s = '2000-03-27*56.75*58.39*2000-03-26*53.10*56.13*2000-03-25*51.50*52.00'
</code>```

答:
You can do a

```<code>new_s = s.split("*")
</code>```

And then use your code on the columns that are datetime formated.

Body:
If my string consisted of just one date I'd use this:

datetime.datetime.strptime(string, '%b %d %Y').strftime('%Y-%m-%d')

But since there are many along the string, I don't know how to proceed. How could I read the string and make the changes only where needed?

So here is my string:

s = 'Mar 27 2000*56.75*58.39*Mar 26 2000*53.10*56.13*Mar 25 2000*51.50*52.00'

and what I expect right after:

s = '2000-03-27*56.75*58.39*2000-03-26*53.10*56.13*2000-03-25*51.50*52.00'

Body:
You can do a

new_s = s.split("*")

And then use your code on the columns that are datetime formated.


问:
Why does setTimeout() clutter my call stack under Chrome DevTools?
I have a function that upon completion re-queues itself with setTimeout().  Could someone explain why Chrome DevTools makes it look like it's calling itself recursively?  My understanding is the call stack ought to be clear on each invocation.

Take this very simple example:

```<code><html>
  <head>
    <script>
      function main() {
        setTimeout(main, 100);  // set breakpoint here
      }
      main();
    </script>
  </head>
  <body></body>
</html>
</code>```

The first time the breakpoint is hit I see this:

After 3 more iterations I see this:

Firefox developer tools does what I expect and just shows one instance of the function on the stack each time the breakpoint is hit.

Is there some kind of subtle reference capture going on under Chrome that I'm not aware of, or is this just a DevTools UI thing?

答:
I just wasted two hours trying to debug something that was NOT broken because I didn't know about the disable async stack traces setting in Chrome Devtools as mentioned in @bsalex's answer.

When implementing the Ajax long-polling technique, you often call the polling function again after getting a response so you can wait for more events/notifications from the server.

Some people use window.setTimeout() function to call the polling function after a certain delay. Logically, the call is recursive but the call stack should not be growing indefinitely with each call. However, the way Chrome shows async stack traces can deceive you into thinking the call stack is growing and in my case I tried all kinds of hacks to no avail trying to fix the code to avoid a stack overflow.

Turns out there's nothing wrong with the code, it's just "a Chrome thing", and disabling async stack traces makes it clear that the stack is behaving as expected. I leave this answer here so people who encounter this problem in a long-polling scenario know what's happening. I wound up on this question by Googling for chrome xhr call stack keeps growing.

Body:
I have a function that upon completion re-queues itself with setTimeout().  Could someone explain why Chrome DevTools makes it look like it's calling itself recursively?  My understanding is the call stack ought to be clear on each invocation.

Take this very simple example:

The first time the breakpoint is hit I see this:

After 3 more iterations I see this:

Firefox developer tools does what I expect and just shows one instance of the function on the stack each time the breakpoint is hit.

Is there some kind of subtle reference capture going on under Chrome that I'm not aware of, or is this just a DevTools UI thing?


问:
Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException) error with Selenium and Geckodriver
Here's the situation: I'm using Behat to run acceptance tests on Symfony. To do so, I start a Selenium instance with the Geckodriver, then I run Behat. Everything works fine on local (great!).

But when it runs on Github action, it fails. I've check the versions, I've even versioned the geckodriver and selenium.jar files to use exactly the same (despite they already exist on github action), but nothing works.

So I'm looking for any help to debug this error. Here's the commands and their results:

```<code>$ java -jar -Dwebdriver.gecko.driver=/usr/local/share/gecko_driver /usr/share/java/selenium-server-standalone.jar &

14:19:46.106 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
14:19:46.369 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 4444
2020-05-29 14:19:46.780:INFO::main: Logging initialized @1350ms to org.seleniumhq.jetty9.util.log.StdErrLog
14:19:47.657 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet
14:19:47.758 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 4444
</code>```

```<code>./vendor/bin/behat -s acceptance

Could not open connection: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'fv-az33', ip: '10.1.0.4', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-1022-azure', java.version: '1.8.0_252'
Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException)
</code>```

答:
This error message...

```<code>Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException)
</code>```

...implies that the GeckoDriver wasn't recognized back by the Browsing Context i.e. Firefox browser.

Solution

Ensure that:

JDK is upgraded to current levels JDK 8u251.

Selenium is upgraded to current levels Version 3.141.59.

GeckoDriver is upgraded to GeckoDriver v0.26.0 level.

Firefox is upgraded to current Firefox v76.0 levels.

GeckoDriver is present in the desired location.

GeckoDriver is having executable permission for non-root users.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your Test as a non-root user.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Reference

You can find a couple of relevant discussions in:

Driver info: driver.version: unknown with ChromeDriver Chrome using Selenium and Python

Body:
Here's the situation: I'm using Behat to run acceptance tests on Symfony. To do so, I start a Selenium instance with the Geckodriver, then I run Behat. Everything works fine on local (great!).

But when it runs on Github action, it fails. I've check the versions, I've even versioned the geckodriver and selenium.jar files to use exactly the same (despite they already exist on github action), but nothing works.

So I'm looking for any help to debug this error. Here's the commands and their results:

$ java -jar -Dwebdriver.gecko.driver=/usr/local/share/gecko_driver /usr/share/java/selenium-server-standalone.jar &

14:19:46.106 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
14:19:46.369 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 4444
2020-05-29 14:19:46.780:INFO::main: Logging initialized @1350ms to org.seleniumhq.jetty9.util.log.StdErrLog
14:19:47.657 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet
14:19:47.758 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 4444

./vendor/bin/behat -s acceptance

Could not open connection: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'fv-az33', ip: '10.1.0.4', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-1022-azure', java.version: '1.8.0_252'
Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException)

Body:
This error message...

Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException)

...implies that the GeckoDriver wasn't recognized back by the Browsing Context i.e. Firefox browser.

Solution

Ensure that:

JDK is upgraded to current levels JDK 8u251.

Selenium is upgraded to current levels Version 3.141.59.

GeckoDriver is upgraded to GeckoDriver v0.26.0 level.

Firefox is upgraded to current Firefox v76.0 levels.

GeckoDriver is present in the desired location.

GeckoDriver is having executable permission for non-root users.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your Test as a non-root user.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Reference

You can find a couple of relevant discussions in:

Driver info: driver.version: unknown with ChromeDriver Chrome using Selenium and Python


问:
System.ArgumentNullException: 'Value cannot be null error
I'm very new to MVC and I'm trying to create an upload file input type of form that allows the user to upload a file, it reads the contents and displays them in a table. but I keep getting this error.
The line that gives me this error is the if Model.Count line in my view and I'm not sure how to resolve it.

Here's my code:

Controller:

```<code>      public ActionResult Index()
    {
        return View(new List<CategoryModel>());
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        List<CategoryModel> categories = new List<CategoryModel>();
        string filePath = string.Empty;
        if (postedFile != null)
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);

            //Read the contents of CSV file.
            string csvData = System.IO.File.ReadAllText(filePath);

            //Execute a loop over the rows.
            foreach (string row in csvData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    categories.Add(new CategoryModel
                    {
                        CategoryID = Convert.ToInt32(row.Split(',')[0]),
                        Name = row.Split(',')[1],
                        Item = row.Split(',')[2]
                    });
                }
            }
        }

        return View();
    }
}
</code>```

}

And Model:

```<code>{
public class CategoryModel
{
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public string Item { get; set; }
}
</code>```

And View:

```<code> @{
    ViewBag.Title = "View";
}

<h2>View</h2>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <span>Select File:</span>
        <input type="file" name="postedFile" />
        <hr />
        <input type="submit" value="Upload" />
    }
    @if (Model.Count() > 0)
    {
        <hr />
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th>CategoryID</th>
                <th>Name</th>
                <th>Item</th>
            </tr>
            @foreach (CategoryModel category in Model)
            {
                <tr>
                    <td>@category.CategoryID</td>
                    <td>@category.Name</td>
                    <td>@category.Item</td>
                </tr>
            }
        </table>
    }
</body>
</html>
</code>```

答:
When you do this in your controller action:

```<code>return View();
</code>```

You are not passing a model to the view, so Model in the view is null.  When you try to call extension methods (like .Count()) on a null reference, that's the error you get.  (Since it's technically not a NullReferenceException, but rather the extension method checking if the first argument is null and throwing an exception.)

You'll need to either check for null in your view, or always pass an instance of the model.  Like you do in your first controller action:

```<code>return View(new List<CategoryModel>());
</code>```

As an aside, after a successful POST action it's generally customary to redirect the user instead of return the view.  That way the browser sends a new HTTP GET request for the redirect so if the user reloads the page it doesn't re-POST the form, but just reloads the GET.

So instead of this:

```<code>return View();
</code>```

You might do this:

```<code>return RedirectToAction("Index");
</code>```

Body:
I'm very new to MVC and I'm trying to create an upload file input type of form that allows the user to upload a file, it reads the contents and displays them in a table. but I keep getting this error.
The line that gives me this error is the if Model.Count line in my view and I'm not sure how to resolve it.

Here's my code:

Controller:

      public ActionResult Index()
    {
        return View(new List<CategoryModel>());
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        List<CategoryModel> categories = new List<CategoryModel>();
        string filePath = string.Empty;
        if (postedFile != null)
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);

            //Read the contents of CSV file.
            string csvData = System.IO.File.ReadAllText(filePath);

            //Execute a loop over the rows.
            foreach (string row in csvData.Split('\n'))
            {
                if (!string.IsNullOrEmpty(row))
                {
                    categories.Add(new CategoryModel
                    {
                        CategoryID = Convert.ToInt32(row.Split(',')[0]),
                        Name = row.Split(',')[1],
                        Item = row.Split(',')[2]
                    });
                }
            }
        }

        return View();
    }
}

}

And Model:

{
public class CategoryModel
{
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public string Item { get; set; }
}

And View:

 @{
    ViewBag.Title = "View";
}

View

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        Select File:
        <input type="file" name="postedFile" />

        <input type="submit" value="Upload" />
    }
    @if (Model.Count() > 0)
    {

                CategoryID
                Name
                Item

            @foreach (CategoryModel category in Model)
            {

                    @category.CategoryID
                    @category.Name
                    @category.Item

            }

    }

Body:
When you do this in your controller action:

return View();

You are not passing a model to the view, so Model in the view is null.  When you try to call extension methods (like .Count()) on a null reference, that's the error you get.  (Since it's technically not a NullReferenceException, but rather the extension method checking if the first argument is null and throwing an exception.)

You'll need to either check for null in your view, or always pass an instance of the model.  Like you do in your first controller action:

return View(new List<CategoryModel>());

As an aside, after a successful POST action it's generally customary to redirect the user instead of return the view.  That way the browser sends a new HTTP GET request for the redirect so if the user reloads the page it doesn't re-POST the form, but just reloads the GET.

So instead of this:

return View();

You might do this:

return RedirectToAction("Index");


问:
Pick multiple images from gallery
How to read/retrieve paths or Uri[] when I select multiple images from gallery?

I want to call this:

```<code>Uri[] originalUri = data.getData();
</code>```

But in reality I'm getting this  only, fetching only one Uri:

```<code> Uri originalUri = data.getData();
</code>```

答:
here's my take of it in Kotlin. This call is from a fragment, and should work in an activity with little to no tweaking.</p>

```<code>//const lives in companion or above class definition
private const val PHOTO_PICKER_REQUEST_CODE = 36

private fun launchPhotoPicker() {
    Intent(Intent.ACTION_PICK).apply {
        putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        type = "image/*"
    }.let {
        startActivityForResult(it, PHOTO_PICKER_REQUEST_CODE)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == PHOTO_PICKER_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            val selectedPhotoUris = mutableListOf<Uri>()

            data?.data?.let {
                selectedPhotoUris.add(it)
            }

            data?.clipData?.let { clipData ->
                for (i in 0 until clipData.itemCount) {
                    clipData.getItemAt(i).uri.let { uri ->
                        selectedPhotoUris.add(uri)
                    }
                }
            }

            //data.data is usually the first item in clipdata
            //I prefer to not make assumptions and just squash dupes
            //I don't trust like that
            val uris = selectedPhotoUris.distinctBy { it.toString() }

            handlePhotoUris(uris)
        }
    }

    super.onActivityResult(requestCode, resultCode, data)
}

private fun handlePhotoUris(uris: List<Uri>) {
    Log.d("photoPicking", "handle uris size: ${it.size}")
    //do stuff here
}
</code>```

Title: Pick multiple images from gallery

Body:
How to read/retrieve paths or Uri[] when I select multiple images from gallery?

I want to call this:

Uri[] originalUri = data.getData();

But in reality I'm getting this  only, fetching only one Uri:

 Uri originalUri = data.getData();

Body:
here's my take of it in Kotlin. This call is from a fragment, and should work in an activity with little to no tweaking.

//const lives in companion or above class definition
private const val PHOTO_PICKER_REQUEST_CODE = 36

private fun launchPhotoPicker() {
    Intent(Intent.ACTION_PICK).apply {
        putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        type = "image/*"
    }.let {
        startActivityForResult(it, PHOTO_PICKER_REQUEST_CODE)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == PHOTO_PICKER_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

            val selectedPhotoUris = mutableListOf<Uri>()

            data?.data?.let {
                selectedPhotoUris.add(it)
            }

            data?.clipData?.let { clipData ->
                for (i in 0 until clipData.itemCount) {
                    clipData.getItemAt(i).uri.let { uri ->
                        selectedPhotoUris.add(uri)
                    }
                }
            }

            //data.data is usually the first item in clipdata
            //I prefer to not make assumptions and just squash dupes
            //I don't trust like that
            val uris = selectedPhotoUris.distinctBy { it.toString() }

            handlePhotoUris(uris)
        }
    }

    super.onActivityResult(requestCode, resultCode, data)
}

private fun handlePhotoUris(uris: List<Uri>) {
    Log.d("photoPicking", "handle uris size: ${it.size}")
    //do stuff here
}


问:
Parallax elements on scroll
Fiddle

I have a horizontal page with multiple sections on it. On section 2 I have three images. When I scroll section 2 into view, I want the images to move 50px in the opposite scroll direction.

I have two problems which I can't figure out due to the layout of this page (horizontal instead of vertical):

how to detect when I reach section 2

how to move the images by ~50px in the opposite direction of the scroll and make it as smooth as possible

I use this code to figure out the direction of the scroll

```<code>var $scrollWrapper = $('.scroll_wrapper');
var $scrollBtn = $('#scrollBtn');
var $scrollOuterWrapper = $('.scroll_outer-wrapper');

$scrollWrapper.scrollTop(0)
$('#scrollBtn').on('click', function() {
  $scrollWrapper.scrollTop($scrollWrapper.scrollTop() + 100)
});

var lastScrollTop = 0;

$scrollOuterWrapper.on('scroll', function() {
  var st = $(this).scrollTop();
  var endOfWrapper = $(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight;
  if (st > lastScrollTop){
    // down scroll
    console.log('downscroll');

    // parallax elements - move to front
    // ??
    $moveElement = $('.move-on-scroll');

    $moveElement.each(function() {
      var firstTop = $(this).offset().top;
      var wrapperScrollTop = $scrollOuterWrapper.scrollTop();
      var shiftDistance = (firstTop - wrapperScrollTop)*0.02;

      $(this).css("transform","translateX("+shiftDistance+"px)");
    });

  } else {
    // upscroll
     console.log('upscroll');

     // parallax elements - move to back
     // ??
  }
  lastScrollTop = st;
});
</code>```

Here's also a snippet:

var $scrollWrapper = $('.scroll_wrapper');
var $scrollBtn = $('#scrollBtn');
var $scrollOuterWrapper = $('.scroll_outer-wrapper');

$scrollWrapper.scrollTop(0)
$('#scrollBtn').on('click', function() {
  $scrollWrapper.scrollTop($scrollWrapper.scrollTop() + 100)
});

var lastScrollTop = 0;

$scrollOuterWrapper.on('scroll', function() {
  var st = $(this).scrollTop();
  var endOfWrapper = $(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight;
  if (st > lastScrollTop){
    // down scroll
    console.log('downscroll');

    // parallax elements - move to front
    // ??
    $moveElement = $('.move-on-scroll');

    $moveElement.each(function() {
      var firstTop = $(this).offset().top;
      var wrapperScrollTop = $scrollOuterWrapper.scrollTop();
      var shiftDistance = (firstTop - wrapperScrollTop)*0.2;

      $(this).css("transform","translateX("+shiftDistance+"px)");
    });

  } else {
    // upscroll
     console.log('upscroll');

     // parallax elements - move to back
     // ??
  }
  lastScrollTop = st;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.scroll_outer-wrapper {
  width: 100vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
}
.scroll_wrapper {
  display: flex;
  flex-direction: row;
  width: 400vw;
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
  transition: transform .5s ease;
}
.scroll_section {
  width: 100vw;
  height: 100vh;
}

.scroll_section.one{background: black; color: white;}
.scroll_section.two{background: white; color: black;}
.scroll_section.three{background: black; color: white;}
.scroll_section.four{background: pink; color: black;}

#scrollBtn {
    position: absolute;
    bottom: 20px;
    right: 20px;
    background-color: darkblue;
    color: white;
    border: none;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    text-transform: uppercase;
    font-size: 12px;
    line-height: 20px;
    cursor: pointer;
}

.move-on-scroll {
  width: 150px;
  height: 150px;
  border: 2px solid red;
  margin: 0 20px;
}

.move-on-scroll img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.two_inner {
  display: flex;
}</code>```

section 1

section 2

section 3

section 4

<button id="scrollBtn">Click to Scroll</button>```

答:
While writing the answer, start thinking. I'm not quite sure, what is the goal. Maybe if you show some images of a result or explain the scenario - i could do more accurate. For now - made this. First line of image starts moving with the second screen. The second line of images start moving from the beginning. View the code in Full page mode.

UPDATED

Simply added transition to CSS for the element, which is transforming with transform via jquery.

```<code>.move-on-scroll {transition: all .5s cubic-bezier(.25,.99,.52,.9);}
</code>```

If you what to correct the ease transition-timing-function - you can create your own cubic-bezier here https://cubic-bezier.com/

var $scrollWrapper = $('.scroll_wrapper');
var $scrollBtn = $('#scrollBtn');
var $scrollOuterWrapper = $('.scroll_outer-wrapper');

// Have no idea, what it shoud do
/*$scrollWrapper.scrollTop(0);
$('#scrollBtn').on('click', function() {
  $scrollWrapper.scrollTop($scrollWrapper.scrollTop() + 100)
});*/

$scrollOuterWrapper.on('scroll', function() {

  var st = $(this).scrollTop();
  var sOneWidth = $('.scroll_section.one').width();

  $moveElement = $('.move-on-scroll');
  $moveElement.each(function() {
    var firstTop = $(this).offset().left;
    var shiftDistance = -st * 0.3;
    // detects, when you reash section 2
    if (st >= sOneWidth) {
      //do something
    }
    $(this).css("transform", "translateX(" + shiftDistance + "px)");
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  margin: 0;
  padding: 0;
}

.scroll_outer-wrapper {
  width: 100vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
}

.scroll_outer-wrapper {
  scrollbar-width: thin;
}

.scroll_outer-wrapper::-webkit-scrollbar {
  width: 6px;
  background-color: #fff;
}

.scroll_outer-wrapper::-webkit-scrollbar-track {
  background-color: #F5F5F5;
  border-radius: 10px;
}

.scroll_outer-wrapper::-webkit-scrollbar-thumb {
  background: #ffa000;
}

.scroll_wrapper {
  display: flex;
  flex-direction: row;
  width: 400vw;
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
  transition: transform .5s ease;
}

.scroll_section {
  width: 100vw;
  height: 100vh;
}

.scroll_section.one {
  background: black;
  color: white;
}

.scroll_section.two {
  background: white;
  color: black;
}

.scroll_section.three {
  background: black;
  color: white;
}

.scroll_section.four {
  background: pink;
  color: black;
}

#scrollBtn {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: darkblue;
  color: white;
  border: none;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  text-transform: uppercase;
  font-size: 12px;
  line-height: 20px;
  cursor: pointer;
}

.move-on-scroll {
  width: 150px;
  height: 150px;
  border: 2px solid red;
  margin: 0 20px;
  transition: all .5s cubic-bezier(.25, .99, .52, .9);
}

.move-on-scroll img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.two_inner {
  display: flex;
  justify-content: flex-end;
  overflow: hidden;
}</code>```

section 1

section 2

section 3

section 4

<button id="scrollBtn">Click to Scroll</button>```

Title: Parallax elements on scroll

Body:
Fiddle

I have a horizontal page with multiple sections on it. On section 2 I have three images. When I scroll section 2 into view, I want the images to move 50px in the opposite scroll direction.

I have two problems which I can't figure out due to the layout of this page (horizontal instead of vertical):

how to detect when I reach section 2

how to move the images by ~50px in the opposite direction of the scroll and make it as smooth as possible

I use this code to figure out the direction of the scroll

var $scrollWrapper = $('.scroll_wrapper');
var $scrollBtn = $('#scrollBtn');
var $scrollOuterWrapper = $('.scroll_outer-wrapper');

$scrollWrapper.scrollTop(0)
$('#scrollBtn').on('click', function() {
  $scrollWrapper.scrollTop($scrollWrapper.scrollTop() + 100)
});

var lastScrollTop = 0;

$scrollOuterWrapper.on('scroll', function() {
  var st = $(this).scrollTop();
  var endOfWrapper = $(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight;
  if (st > lastScrollTop){
    // down scroll
    console.log('downscroll');

    // parallax elements - move to front
    // ??
    $moveElement = $('.move-on-scroll');

    $moveElement.each(function() {
      var firstTop = $(this).offset().top;
      var wrapperScrollTop = $scrollOuterWrapper.scrollTop();
      var shiftDistance = (firstTop - wrapperScrollTop)*0.02;

      $(this).css("transform","translateX("+shiftDistance+"px)");
    });

  } else {
    // upscroll
     console.log('upscroll');

     // parallax elements - move to back
     // ??
  }
  lastScrollTop = st;
});

Here's also a snippet:

var $scrollWrapper = $('.scroll_wrapper');
var $scrollBtn = $('#scrollBtn');
var $scrollOuterWrapper = $('.scroll_outer-wrapper');

$scrollWrapper.scrollTop(0)
$('#scrollBtn').on('click', function() {
  $scrollWrapper.scrollTop($scrollWrapper.scrollTop() + 100)
});

var lastScrollTop = 0;

$scrollOuterWrapper.on('scroll', function() {
  var st = $(this).scrollTop();
  var endOfWrapper = $(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight;
  if (st > lastScrollTop){
    // down scroll
    console.log('downscroll');

    // parallax elements - move to front
    // ??
    $moveElement = $('.move-on-scroll');

    $moveElement.each(function() {
      var firstTop = $(this).offset().top;
      var wrapperScrollTop = $scrollOuterWrapper.scrollTop();
      var shiftDistance = (firstTop - wrapperScrollTop)*0.2;

      $(this).css("transform","translateX("+shiftDistance+"px)");
    });

  } else {
    // upscroll
     console.log('upscroll');

     // parallax elements - move to back
     // ??
  }
  lastScrollTop = st;
});

.scroll_outer-wrapper {
  width: 100vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
}
.scroll_wrapper {
  display: flex;
  flex-direction: row;
  width: 400vw;
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
  transition: transform .5s ease;
}
.scroll_section {
  width: 100vw;
  height: 100vh;
}

.scroll_section.one{background: black; color: white;}
.scroll_section.two{background: white; color: black;}
.scroll_section.three{background: black; color: white;}
.scroll_section.four{background: pink; color: black;}

#scrollBtn {
    position: absolute;
    bottom: 20px;
    right: 20px;
    background-color: darkblue;
    color: white;
    border: none;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    text-transform: uppercase;
    font-size: 12px;
    line-height: 20px;
    cursor: pointer;
}

.move-on-scroll {
  width: 150px;
  height: 150px;
  border: 2px solid red;
  margin: 0 20px;
}

.move-on-scroll img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.two_inner {
  display: flex;
}

section 1

section 2

section 3

section 4

<button id="scrollBtn">Click to Scroll</button>

Body:
While writing the answer, start thinking. I'm not quite sure, what is the goal. Maybe if you show some images of a result or explain the scenario - i could do more accurate. For now - made this. First line of image starts moving with the second screen. The second line of images start moving from the beginning. View the code in Full page mode.

UPDATED

Simply added transition to CSS for the element, which is transforming with transform via jquery.

.move-on-scroll {transition: all .5s cubic-bezier(.25,.99,.52,.9);}

If you what to correct the ease transition-timing-function - you can create your own cubic-bezier here https://cubic-bezier.com/

var $scrollWrapper = $('.scroll_wrapper');
var $scrollBtn = $('#scrollBtn');
var $scrollOuterWrapper = $('.scroll_outer-wrapper');

// Have no idea, what it shoud do
/*$scrollWrapper.scrollTop(0);
$('#scrollBtn').on('click', function() {
  $scrollWrapper.scrollTop($scrollWrapper.scrollTop() + 100)
});*/

$scrollOuterWrapper.on('scroll', function() {

  var st = $(this).scrollTop();
  var sOneWidth = $('.scroll_section.one').width();

  $moveElement = $('.move-on-scroll');
  $moveElement.each(function() {
    var firstTop = $(this).offset().left;
    var shiftDistance = -st * 0.3;
    // detects, when you reash section 2
    if (st >= sOneWidth) {
      //do something
    }
    $(this).css("transform", "translateX(" + shiftDistance + "px)");
  });

});

* {
  box-sizing: border-box;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  margin: 0;
  padding: 0;
}

.scroll_outer-wrapper {
  width: 100vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-100vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
}

.scroll_outer-wrapper {
  scrollbar-width: thin;
}

.scroll_outer-wrapper::-webkit-scrollbar {
  width: 6px;
  background-color: #fff;
}

.scroll_outer-wrapper::-webkit-scrollbar-track {
  background-color: #F5F5F5;
  border-radius: 10px;
}

.scroll_outer-wrapper::-webkit-scrollbar-thumb {
  background: #ffa000;
}

.scroll_wrapper {
  display: flex;
  flex-direction: row;
  width: 400vw;
  transform: rotate(90deg) translateY(-100vh);
  transform-origin: top left;
  transition: transform .5s ease;
}

.scroll_section {
  width: 100vw;
  height: 100vh;
}

.scroll_section.one {
  background: black;
  color: white;
}

.scroll_section.two {
  background: white;
  color: black;
}

.scroll_section.three {
  background: black;
  color: white;
}

.scroll_section.four {
  background: pink;
  color: black;
}

#scrollBtn {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: darkblue;
  color: white;
  border: none;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  text-transform: uppercase;
  font-size: 12px;
  line-height: 20px;
  cursor: pointer;
}

.move-on-scroll {
  width: 150px;
  height: 150px;
  border: 2px solid red;
  margin: 0 20px;
  transition: all .5s cubic-bezier(.25, .99, .52, .9);
}

.move-on-scroll img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.two_inner {
  display: flex;
  justify-content: flex-end;
  overflow: hidden;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scroll_outer-wrapper">
  <div class="scroll_wrapper">
    <section class="scroll_section one">
      <h2>section 1</h2>
    </section>
    <section class="scroll_section two">
      <h2>section 2</h2>
      <div class="two_inner">
        <div class="move-on-scroll">
          <img src="https://images.unsplash.com/photo-1590336751349-f65720fee481?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=80">
        </div>
        <div class="move-on-scroll">
          <img src="https://images.unsplash.com/photo-1590336751349-f65720fee481?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=80">
        </div>
        <div class="move-on-scroll">
          <img src="https://images.unsplash.com/photo-1590336751349-f65720fee481?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=80">
        </div>
      </div>
    </section>
    <section class="scroll_section three">
      <h2>section 3</h2>
    </section>
    <section class="scroll_section four">
      <h2>section 4</h2>
    </section>
  </div>
</div>

<button id="scrollBtn">Click to Scroll</button>