问:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

The ORDER BY clause is invalid in views, inline functions, derived
  tables, subqueries, and common table expressions, unless TOP, OFFSET
  or FOR XML is also specified.

I am getting the above said error while trying to execute the following query. Can anyone please have a look and tell me what am I doing wrong here?

```<code>SELECT
    *
FROM (
    SELECT
        Stockmain.VRNOA,
        item.description as item_description,
        party.name as party_name,
        stockmain.vrdate,
        stockdetail.qty,
        stockdetail.rate,
        stockdetail.amount,
        ROW_NUMBER() OVER (ORDER BY VRDATE) AS RowNum
    FROM StockMain
    INNER JOIN StockDetail
        ON StockMain.stid = StockDetail.stid
    INNER JOIN party
        ON party.party_id = stockmain.party_id
    INNER JOIN item
        ON item.item_id = stockdetail.item_id
    WHERE stockmain.etype='purchase'
    ORDER BY VRDATE DESC
) AS MyDerivedTable
WHERE
    MyDerivedTable.RowNum BETWEEN 1 and 5
</code>```

答:
```<code>ORDER BY column OFFSET 0 ROWS
</code>```

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

```<code>;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM
(
    SELECT * FROM
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
    ) first
    UNION ALL
    SELECT * FROM
    (
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
</code>```

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

Body:
The ORDER BY clause is invalid in views, inline functions, derived
  tables, subqueries, and common table expressions, unless TOP, OFFSET
  or FOR XML is also specified.

I am getting the above said error while trying to execute the following query. Can anyone please have a look and tell me what am I doing wrong here?

SELECT
    *
FROM (
    SELECT
        Stockmain.VRNOA,
        item.description as item_description,
        party.name as party_name,
        stockmain.vrdate,
        stockdetail.qty,
        stockdetail.rate,
        stockdetail.amount,
        ROW_NUMBER() OVER (ORDER BY VRDATE) AS RowNum
    FROM StockMain
    INNER JOIN StockDetail
        ON StockMain.stid = StockDetail.stid
    INNER JOIN party
        ON party.party_id = stockmain.party_id
    INNER JOIN item
        ON item.item_id = stockdetail.item_id
    WHERE stockmain.etype='purchase'
    ORDER BY VRDATE DESC
) AS MyDerivedTable
WHERE
    MyDerivedTable.RowNum BETWEEN 1 and 5

Body:
ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM
(
    SELECT * FROM
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
    ) first
    UNION ALL
    SELECT * FROM
    (
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY


来源: stackexchange

问:
How to create a PayPal subscription order?
I'm using PayPal Checkout API SDK and I successfully created an order using the smart buttons, so when the user click on the paypal button an order is created.  Here's my code for the final capture:

```<code>let request = new paypal.orders.OrdersCreateRequest();
    request.requestBody({
        "intent": "CAPTURE",
        "purchase_units": [{
            "amount": {
                "currency_code": 'EUR',
                "value": '15.00',
            },
            "redirect_urls": {
                "return_url": `${process.env.APP_DOMAIN}/pay/success?session_id={CHECKOUT_SESSION_ID}`,
                "cancel_url": `${process.env.APP_DOMAIN}/pay/cancel?session_id={CHECKOUT_SESSION_ID}`,
            }
        }]
    });
</code>```

What I don't understand is: how can I actually create a subscription order? I need to make a monthly subscription, but I can't find anything in the documentation that allows me to create such a checkout

答:
The Subscriptions API is newer and most SDKs don't support it yet (and if they do support billing plan calls, it's for an older, incompatible version, generally)

So you probably need to implement direct HTTPS API calls (no SDK) to create the necessary Product and Plan. All those curl calls you see in the documentation? Do the equivalent from node.

Then in the last step you pass the resulting plan object to the client-side SPB js.

ContentLicense: CC BY-SA 4.0

Body:
I'm using PayPal Checkout API SDK and I successfully created an order using the smart buttons, so when the user click on the paypal button an order is created.  Here's my code for the final capture:

let request = new paypal.orders.OrdersCreateRequest();
    request.requestBody({
        "intent": "CAPTURE",
        "purchase_units": [{
            "amount": {
                "currency_code": 'EUR',
                "value": '15.00',
            },
            "redirect_urls": {
                "return_url": `${process.env.APP_DOMAIN}/pay/success?session_id={CHECKOUT_SESSION_ID}`,
                "cancel_url": `${process.env.APP_DOMAIN}/pay/cancel?session_id={CHECKOUT_SESSION_ID}`,
            }
        }]
    });

What I don't understand is: how can I actually create a subscription order? I need to make a monthly subscription, but I can't find anything in the documentation that allows me to create such a checkout


问:
BlackBerry - Thread not responding
I'm sorry that this question is a bit vague but I've not been able to get any useful info from debugging.

I have a thread that I call using new Thread().Start, it will then run for a a short time and I receive this message:

Uncaught exception:Application "my app
  name(201)" is not responding; process
  terminated

Now what's frustrating is I am able to run the same process but without a thread, which then locks up my Application but I can see from my Eclipse console that its working without error. So I know their isn't an error with the functions I'm using on the Thread.

I thought perhaps the issue might lie with me using a "InvokeLater" function to update my GUI with the threads progression, I am spamming this pretty hard and I fear its destroying my thread.

Any suggestions?

To expand upon my post, the issue was due to me calling this code ALOT from my other thread:-

```<code> invokeLater(new Runnable()
        {
            public void run()
            {
                _output.setText(_output.getText() + "\n" + msg);
            }
        });
</code>```

This was building up a queue that quickly crashed my application.

My solution to the option was to use the event thread by adding this code to my function:-

```<code>   synchronized(Application.getEventLock()) {
       _output.setText("new text " + System.currentTimeMillis());
   }
</code>```

答: If you are synchronized on some object within the thread while doing something time-consuming, and if your UI thread attempts to synchronize on the same object, it will block until the lock is released.</p>

ContentLicense: CC BY-SA 3.0

Title: BlackBerry - Thread not responding

Body:
I'm sorry that this question is a bit vague but I've not been able to get any useful info from debugging.

I have a thread that I call using new Thread().Start, it will then run for a a short time and I receive this message:

Uncaught exception:Application "my app
  name(201)" is not responding; process
  terminated

Now what's frustrating is I am able to run the same process but without a thread, which then locks up my Application but I can see from my Eclipse console that its working without error. So I know their isn't an error with the functions I'm using on the Thread.

I thought perhaps the issue might lie with me using a "InvokeLater" function to update my GUI with the threads progression, I am spamming this pretty hard and I fear its destroying my thread.

Any suggestions?

To expand upon my post, the issue was due to me calling this code ALOT from my other thread:-

 invokeLater(new Runnable()
        {
            public void run()
            {
                _output.setText(_output.getText() + "\n" + msg);
            }
        });

This was building up a queue that quickly crashed my application.

My solution to the option was to use the event thread by adding this code to my function:-

   synchronized(Application.getEventLock()) {
       _output.setText("new text " + System.currentTimeMillis());
   }


问:
python pandas check value comming under range in another dataframe

my first dataframe

dataframe1=

```<code>id   number  count1 count2
1   5225    10       30
2   2222    3        40
3   7121    30        50
</code>```

second dataframe

dataframe2=

```<code>id  value1  value2
1   4000     6000
3   2500     3300
3   7000     8000
</code>```

output

```<code>id  value1  value2 number count1 count2
1   4000     6000  5225  10       30
3   7000     8000  7121  30       50
</code>```

I tried

```<code>dataframe2['a']=(dataframe1['number']>= dataframe2['value1']) & (dataframe1['number'] <= dataframe2['value2'])
</code>```

it gave True False values in column a, What I want to do is this: For each value in the Dataframe1  "number" column, search if it is equal to or between ANY of the "value1" and "value2" pair values of Dataframe2. Additionally, for this "number1" and "number2" pair values, its respective "id" must match the "id" in Dataframe. If this is all true, then I want to insert along with number, count1 and count2 in dataframe2

答:
First, let's create the dataframes from your example:

DataFrame 1

```<code>import pandas as pd

d1 = {'id': [1, 2, 3],
     'number': [5225, 2222, 7121],
     'count1': [10, 3, 30],
     'count2': [30, 40, 50]}
df1 = pd.DataFrame(data = d1)
print(df1)

id  number  count1  count2
1   5225    10      30
2   2222    3       40
3   7121    30      50
</code>```

DataFrame 2

```<code>d2 = {'id': [1, 3, 3],
     'value1': [4000, 2500, 7000],
     'value2': [6000, 3300, 8000]}
df2 = pd.DataFrame(data = d2)
print(df2)

id  value1  value2
1   4000    6000
3   2500    3300
3   7000    8000
</code>```

One possible solution is to first join the two tables together:

```<code>df3 = df1.join(other = df2.set_index('id'),
              on = 'id')
print(df3)

id  number  count1  count2  value1  value2
1   5225    10      30      4000.0  6000.0
2   2222    3       40      NaN     NaN
3   7121    30      50      2500.0  3300.0
3   7121    30      50      7000.0  8000.0
</code>```

Then filter by multiple conditions:

```<code>df3[(df3['number'] >= df3['value1']) & (df3['number'] <= df3['value2'])]

id  number  count1  count2  value1  value2
1   5225    10      30      4000.0  6000.0
3   7121    30      50      7000.0  8000.0
</code>```

Body:
my first dataframe

dataframe1=

id   number  count1 count2
1   5225    10       30
2   2222    3        40
3   7121    30        50

second dataframe

dataframe2=

id  value1  value2
1   4000     6000
3   2500     3300
3   7000     8000

output

id  value1  value2 number count1 count2
1   4000     6000  5225  10       30
3   7000     8000  7121  30       50

I tried

dataframe2['a']=(dataframe1['number']>= dataframe2['value1']) & (dataframe1['number'] <= dataframe2['value2'])

it gave True False values in column a, What I want to do is this: For each value in the Dataframe1  "number" column, search if it is equal to or between ANY of the "value1" and "value2" pair values of Dataframe2. Additionally, for this "number1" and "number2" pair values, its respective "id" must match the "id" in Dataframe. If this is all true, then I want to insert along with number, count1 and count2 in dataframe2

Body:
First, let's create the dataframes from your example:

DataFrame 1

import pandas as pd

d1 = {'id': [1, 2, 3],
     'number': [5225, 2222, 7121],
     'count1': [10, 3, 30],
     'count2': [30, 40, 50]}
df1 = pd.DataFrame(data = d1)
print(df1)

id  number  count1  count2
1   5225    10      30
2   2222    3       40
3   7121    30      50

DataFrame 2

d2 = {'id': [1, 3, 3],
     'value1': [4000, 2500, 7000],
     'value2': [6000, 3300, 8000]}
df2 = pd.DataFrame(data = d2)
print(df2)

id  value1  value2
1   4000    6000
3   2500    3300
3   7000    8000

One possible solution is to first join the two tables together:

df3 = df1.join(other = df2.set_index('id'),
              on = 'id')
print(df3)

id  number  count1  count2  value1  value2
1   5225    10      30      4000.0  6000.0
2   2222    3       40      NaN     NaN
3   7121    30      50      2500.0  3300.0
3   7121    30      50      7000.0  8000.0

Then filter by multiple conditions:

df3[(df3['number'] >= df3['value1']) & (df3['number'] <= df3['value2'])]

id  number  count1  count2  value1  value2
1   5225    10      30      4000.0  6000.0
3   7121    30      50      7000.0  8000.0


问:
Sort dataframe by month and find the first non-zero value in each column for each month
I need to load a CSV with 200 columns, the first column is a date, into a pandas dataframe in python.  I need to sort through the data and return the first non-zero value for each month. Should I make separate dataframes or each month, and then search? What's the best way to approach this problem?</p>

```<code>df = pd.read_csv('loaddata.csv')
df['DATE'] = pd.to_datetime(df['DATE'], format='%m/%d/%Y')
df['Month']= pd.DatetimeIndex(df['DATE']).month

THe data looks like this:

Date    Data_1   Data_2  Data_3
1/d/y    0         0       1
2/d/y    0         1       2
3/d/y    2         6       0
1/d/y    5         3       45
2/d/y    20        7       90
3/d/y    25        12      18

Returns:
      Data_1   Data_2   Data_3
Jan     5         3       1
Feb     20        7       2
Mar     2         6       18

</code>```

答:
You got an error for Feb, column Data_2: the first non-zero is 1, not 7.

Here's one way to do it:

```<code>def first_non_zero(col):
    """Return the first non-zero value of a column, or nan if the column is all-zero"""
    head = col[col != 0].head(1)
    return np.nan if head.empty else head.values

df.groupby('Month').apply(lambda group: group[['Data_1', 'Data_2', 'Data_3']].apply(first_non_zero)) \
    .reset_index(level=1, drop=True)
</code>```

Result:

```<code>       Data_1  Data_2  Data_3
Month
1           5       3       1
2          20       1       2
3           2       6      18
</code>```

Body:
I need to load a CSV with 200 columns, the first column is a date, into a pandas dataframe in python.  I need to sort through the data and return the first non-zero value for each month. Should I make separate dataframes or each month, and then search? What's the best way to approach this problem?

df = pd.read_csv('loaddata.csv')
df['DATE'] = pd.to_datetime(df['DATE'], format='%m/%d/%Y')
df['Month']= pd.DatetimeIndex(df['DATE']).month

THe data looks like this:

Date    Data_1   Data_2  Data_3
1/d/y    0         0       1
2/d/y    0         1       2
3/d/y    2         6       0
1/d/y    5         3       45
2/d/y    20        7       90
3/d/y    25        12      18

Returns:
      Data_1   Data_2   Data_3
Jan     5         3       1
Feb     20        7       2
Mar     2         6       18

Body:
You got an error for Feb, column Data_2: the first non-zero is 1, not 7.

Here's one way to do it:

def first_non_zero(col):
    """Return the first non-zero value of a column, or nan if the column is all-zero"""
    head = col[col != 0].head(1)
    return np.nan if head.empty else head.values

df.groupby('Month').apply(lambda group: group[['Data_1', 'Data_2', 'Data_3']].apply(first_non_zero)) \
    .reset_index(level=1, drop=True)

Result:

       Data_1  Data_2  Data_3
Month
1           5       3       1
2          20       1       2
3           2       6      18


问:
Getting non-zero data and positions from 2D array in Python
I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.

Is there any way that I can get the value and the position at the same time?

```<code>import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])

res = zip(*np.nonzero(groupMatrix))

print(list(res))
</code>```

The result I got is [(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

But I hope the result can show the position with value.

For example, (x, y, z): x, y represent the position and z represents the value at the point.

(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2).

Thank you for your help!!!

答:
Use np.vstack and numpy multidimensional indexing.

```<code>i   = np.nonzero(arr)

res = np.vstack([i, arr[i]])
</code>```

```<code>array([[0, 0, 1, 2, 3, 3, 3],
       [0, 1, 0, 3, 0, 1, 3],
       [1, 1, 1, 2, 3, 3, 2]])
</code>```

If you really need a list of tuples with the information, you can use list(zip(*...))

```<code>>>> list(zip(*res))
[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]
</code>```

Body:
I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.

Is there any way that I can get the value and the position at the same time?

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])

res = zip(*np.nonzero(groupMatrix))

print(list(res))

The result I got is [(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

But I hope the result can show the position with value.

For example, (x, y, z): x, y represent the position and z represents the value at the point.

(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2).

Thank you for your help!!!

Body:
Use np.vstack and numpy multidimensional indexing.

i   = np.nonzero(arr)

res = np.vstack([i, arr[i]])

array([[0, 0, 1, 2, 3, 3, 3],
       [0, 1, 0, 3, 0, 1, 3],
       [1, 1, 1, 2, 3, 3, 2]])

If you really need a list of tuples with the information, you can use list(zip(*...))

>>> list(zip(*res))
[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]


问:
SQL XML output limited number of records
I am trying to use SELECT statement and output data as XML Elements But when I run the script, the output is not the full result, it stops at the record 1600, I have more than 5K records in that statement that needs to output in XML.

Here is my code.

```<code>DECLARE @XMLSessionData  xml

SET @XMLData=
(SELECT
'Document' AS "Type",
'' AS "Account",
 Name AS "NameClass",
2 AS "CodeType",
LastName AS "UserName/FamilyName",
FirstName AS "UserName/GivenName",
'' AS "UserName/initials",
NumberQuery AS "QueryCount",
IDNumber AS "UserNumber",
UserAddress AS "UserAddress/AddressLine1",
'' AS "UserAddress/AddressLine2",
'' AS "UserAddress/AddressLine3",
City AS "UserAddress/City",
State AS "UserAddress/State",
'USA' AS "UserAddress/CountryCode",
UserZipCode AS "UserAddress/ZipCode",
FROM tbSessonDocuments
FOR XML PATH ('Documet'), ELEMENTS)

SELECT @XMLSessionData
</code>```

The output is correct I have used the validate the XML against the Schema but the number of records that it's able to output as XML is limited, now it works fine if I decrease the number of elements it grabs the full result

答:
You can try to adjust settings in SSMS.

Select in the menu Tools/Options/Query Results/SQL Server/Results to Grid.

Maximum Characters Retrieved

XML data: Unlimited.

Body:
I am trying to use SELECT statement and output data as XML Elements But when I run the script, the output is not the full result, it stops at the record 1600, I have more than 5K records in that statement that needs to output in XML.

Here is my code.

DECLARE @XMLSessionData  xml

SET @XMLData=
(SELECT
'Document' AS "Type",
'' AS "Account",
 Name AS "NameClass",
2 AS "CodeType",
LastName AS "UserName/FamilyName",
FirstName AS "UserName/GivenName",
'' AS "UserName/initials",
NumberQuery AS "QueryCount",
IDNumber AS "UserNumber",
UserAddress AS "UserAddress/AddressLine1",
'' AS "UserAddress/AddressLine2",
'' AS "UserAddress/AddressLine3",
City AS "UserAddress/City",
State AS "UserAddress/State",
'USA' AS "UserAddress/CountryCode",
UserZipCode AS "UserAddress/ZipCode",
FROM tbSessonDocuments
FOR XML PATH ('Documet'), ELEMENTS)

SELECT @XMLSessionData

The output is correct I have used the validate the XML against the Schema but the number of records that it's able to output as XML is limited, now it works fine if I decrease the number of elements it grabs the full result


问:
How to monitor progress of ssh file transfer and output to a log file
I'm writing a bash script to periodically transfer data to a remote system.  I have a local command that generates a stream, and a remote command that consumes it, so I'm doing something like this:

```<code>generate_data | ssh remoteserver.example.com consume_data
</code>```

(Where I have ssh keys set up so I can do this non-interactively.)  This works fine.  However, since this will be an automated process (running as a cron job) and may sometimes be transferring large amounts of data on limited bandwidth, I'd like to be able place periodic progress updates in my log file.  I had thought to use pv (pipe viewer) for this, and this is the best I could come up with:

```<code>generate_data | pv -fb | ssh remoteserver.example.com consume_data
</code>```

Again, it works... but pv was really written with terminal output in mind, so I end up with a mess in the log that looks like

```<code>2.06MB^M2.19MB^M2.37MB^M 2.5MB^M2.62MB^M2.87MB^M3MB^M3.12MB^M3.37MB
</code>```

I'd prefer log messages along the lines of

```<code><timestamp> 2.04MB transferred...
<timestamp> 3.08MB transferred...
</code>```

If anybody has any clever ideas of how to do this, either with different arguments to pv or via some other mechanism, I'd be grateful.

EDIT: Thanks for the answers so far.  Of course there are a lot of possible home-brewed solutions; I was hoping to find something that would work "out of the box."  (Not that I'm ruling out home-brewed; it may be the easiest thing in the end.  Since pv already does 98% of what I need, I'd prefer not to re-invent it.)

PostScript: Here's the line I ended up using, in hopes it might help someone else at some point.

```<code>{ generate_data | pv -fbt -i 60 2>&3 | ssh remoteserver consume_data } 3>&1 | awk -vRS='\r' '{print $1 " transferred in " $2; fflush();}' >> logfile
</code>```

答:
You might have a look at bar: http://clpbar.sourceforge.net/

Bar is a simple tool to copy a stream
  of data and print a display for the
  user on stderr showing (a) the amount
  of data passed, (b) the throughput of
  the data transfer, and (c) the
  transfer time, or, if the total size
  of the data stream is known, the
  estimated time remaining, what
  percentage of the data transfer has
  been completed, and a progress bar.

Bar was originally written for the
  purpose of estimating the amount of
  time needed to transfer large amounts
  (many, many gigabytes) of data across
  a network. (Usually in an SSH/tar
  pipe.)

Body:
I'm writing a bash script to periodically transfer data to a remote system.  I have a local command that generates a stream, and a remote command that consumes it, so I'm doing something like this:

generate_data | ssh remoteserver.example.com consume_data

(Where I have ssh keys set up so I can do this non-interactively.)  This works fine.  However, since this will be an automated process (running as a cron job) and may sometimes be transferring large amounts of data on limited bandwidth, I'd like to be able place periodic progress updates in my log file.  I had thought to use pv (pipe viewer) for this, and this is the best I could come up with:

generate_data | pv -fb | ssh remoteserver.example.com consume_data

Again, it works... but pv was really written with terminal output in mind, so I end up with a mess in the log that looks like

2.06MB^M2.19MB^M2.37MB^M 2.5MB^M2.62MB^M2.87MB^M3MB^M3.12MB^M3.37MB

I'd prefer log messages along the lines of

<timestamp> 2.04MB transferred...
<timestamp> 3.08MB transferred...

If anybody has any clever ideas of how to do this, either with different arguments to pv or via some other mechanism, I'd be grateful.

EDIT: Thanks for the answers so far.  Of course there are a lot of possible home-brewed solutions; I was hoping to find something that would work "out of the box."  (Not that I'm ruling out home-brewed; it may be the easiest thing in the end.  Since pv already does 98% of what I need, I'd prefer not to re-invent it.)

PostScript: Here's the line I ended up using, in hopes it might help someone else at some point.

{ generate_data | pv -fbt -i 60 2>&3 | ssh remoteserver consume_data } 3>&1 | awk -vRS='\r' '{print $1 " transferred in " $2; fflush();}' >> logfile


问:
How to define logging in one place in Python?
I am new Python and I want to define the following logging code in python in one place so that it can be used in other python files(class or non-class). In case of Java, we use log4j or slf4j as part of jar files and we simply define as Logger logger = Logger.getLogger("class name"), I want achieve exactly like this so that I can use loger in any python module/s. Currently I define the config in all the classes.

import logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ]
)
```

I have also gone through this SO link Using logging in multiple modules

Also please suggest the most recommended approach for medium to large project having more number of python files.

答:
As per this link https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/, the author has mentioned a better practice. There may be better recommended approach.
You have to do in the following manner.

Define logging.json file as mentioned in the link.

Define a python file called LogSetup.py and add below the code.

```<code>def setup_logging(default_path='logging.json', default_level=logging.DEBUG, env_key='LOG_CFG'):
    """Setup logging configuration"""
    path = default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, 'rt') as f:
            config = json.load(f)
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)
</code>```

Call the above file like this LogSetup.setup_logging() in the main method.
I provide below the code snippet.

logger = logging.getLogger(name)

```<code>if __name__ == '__main__':
    LogSetup.setup_logging()
    logger.debug("This is a debug message ...")
</code>```

It looks good for me, others may recommend the better approaches.

Body:
I am new Python and I want to define the following logging code in python in one place so that it can be used in other python files(class or non-class). In case of Java, we use log4j or slf4j as part of jar files and we simply define as Logger logger = Logger.getLogger("class name"), I want achieve exactly like this so that I can use loger in any python module/s. Currently I define the config in all the classes.

import logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ]
)

I have also gone through this SO link Using logging in multiple modules

Also please suggest the most recommended approach for medium to large project having more number of python files.

Body:
As per this link https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/, the author has mentioned a better practice. There may be better recommended approach.
You have to do in the following manner.

Define logging.json file as mentioned in the link.

Define a python file called LogSetup.py and add below the code.

def setup_logging(default_path='logging.json', default_level=logging.DEBUG, env_key='LOG_CFG'):
    """Setup logging configuration"""
    path = default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, 'rt') as f:
            config = json.load(f)
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)

Call the above file like this LogSetup.setup_logging() in the main method.
I provide below the code snippet.

logger = logging.getLogger(name)

if __name__ == '__main__':
    LogSetup.setup_logging()
    logger.debug("This is a debug message ...")

It looks good for me, others may recommend the better approaches.


问:
Scheduling an API call to save results to a database
I currently have a MERN stack web application hosted on Zeit, which is a simple stock simulator. I would like to schedule an API call to an endpoint every weekday at 4:00pm to pull some market data for the day, and save it to a MongoDB database. What is the best way to do this? For reference I am familiar with Microsoft Azure, and AWS. Thanks</p>

答:
In AWS, you can use a CloudWatch events rule that triggers a lambda function every weekday at 4:00pm.
Lambda function should have code to read the data and save data in MongoDB.

How to schedule Cloudwatch Event


答:
You can use Azure Functions with time trigger for it:

function.json

```<code>{
    "schedule": "0 0 4 * * *",
    "name": "myTimer",
    "type": "timerTrigger",
    "direction": "in"
}
</code>```

JavaScript code:

```<code>module.exports = function (context, myTimer) {
    var timeStamp = new Date().toISOString();

    if (myTimer.IsPastDue)
    {
        context.log('Node is running late!');
    }
    context.log('Node timer trigger function ran!', timeStamp);
    //LOGIC TO PERFORM REQUEST / INSERT  on Mongo

    context.done();
};
</code>```

more info: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=javascript

Title: Scheduling an API call to save results to a database

Body: I currently have a MERN stack web application hosted on Zeit, which is a simple stock simulator. I would like to schedule an API call to an endpoint every weekday at 4:00pm to pull some market data for the day, and save it to a MongoDB database. What is the best way to do this? For reference I am familiar with Microsoft Azure, and AWS. Thanks

Body:
You can use Azure Functions with time trigger for it:

function.json

{
    "schedule": "0 0 4 * * *",
    "name": "myTimer",
    "type": "timerTrigger",
    "direction": "in"
}

JavaScript code:

module.exports = function (context, myTimer) {
    var timeStamp = new Date().toISOString();

    if (myTimer.IsPastDue)
    {
        context.log('Node is running late!');
    }
    context.log('Node timer trigger function ran!', timeStamp);
    //LOGIC TO PERFORM REQUEST / INSERT  on Mongo

    context.done();
};

more info: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=javascript


问:
randomize observations by groups (blocks) without replacement
This is a follow up question. The answers in the previous question are doing the random sampling with replacement. How can I change the code so that I assign each observation to on of J "urn" without putting the observation back in the 'lottery'?

This is the code I have right now:

```<code>set.seed(9782)
I <- 500
g <- 10
library(dplyr)

anon_id <- function(n = 1, lenght = 12) {
  randomString <- c(1:n)
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, letters, LETTERS),
                                    lenght, replace = TRUE),
                             collapse = "")
  }
  return(randomString)
}

df <- data.frame(id = anon_id(n = I, lenght = 16),
                 group = sample(1:g, I, T))

J <- 3
p <- c(0.25, 0.5, 0.25)

randomize <- function(data, urns=2, block_id = NULL, p=NULL, seed=9782) {
  if(is.null(p)) p <- rep(1/urns, urns)
  if(is.null(block_id)){
    df1 <- data %>%
      mutate(Treatment = sample(x = c(1:urns),
                                size = n(),
                                replace = T,
                                prob = p))
    return(df1)
  }else{
    df1 <- data %>% group_by_(block_id) %>%
      mutate(Treatment = sample(x = c(1:urns),
                                size = n(),
                                replace = T,
                                prob = p))
  }
}

df1 <- randomize(data = df, urns = J, block_id = "group", p = p, seed = 9782)
</code>```

If I change replace = T to replace = F I get the following error:

Error: cannot take a sample larger than the population when 'replace = FALSE'

Clarification of my objective:

Suppose that I have 10 classrooms (or villages, or something like that). To keep it simple, suppose each classroom has 20 students (in reality they will have N_j). Classroom per classroom, I want to assign each student to one of J groups, for example J=3. P says the fraction that will be assigned to each group. For example 25% to group 1 40% to group 2 and 35% to group 3.

答:
My answer to your other question is without replacement, as can be seen below:</p>

```<code>
block_rand <-  as.tibble(randomizr::block_ra(blocks = df$group, conditions = c("urn_1","urn_2","urn_3")))

df2 <- as.tibble(bind_cols(df, block_rand))

df2 %>% janitor::tabyl(group, value)

df2 %>%
  group_by(id) %>%
  filter(n()>1) %>%
  str()
</code>```

Body:
This is a follow up question. The answers in the previous question are doing the random sampling with replacement. How can I change the code so that I assign each observation to on of J "urn" without putting the observation back in the 'lottery'?

This is the code I have right now:

set.seed(9782)
I <- 500
g <- 10
library(dplyr)

anon_id <- function(n = 1, lenght = 12) {
  randomString <- c(1:n)
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, letters, LETTERS),
                                    lenght, replace = TRUE),
                             collapse = "")
  }
  return(randomString)
}

df <- data.frame(id = anon_id(n = I, lenght = 16),
                 group = sample(1:g, I, T))

J <- 3
p <- c(0.25, 0.5, 0.25)

randomize <- function(data, urns=2, block_id = NULL, p=NULL, seed=9782) {
  if(is.null(p)) p <- rep(1/urns, urns)
  if(is.null(block_id)){
    df1 <- data %>%
      mutate(Treatment = sample(x = c(1:urns),
                                size = n(),
                                replace = T,
                                prob = p))
    return(df1)
  }else{
    df1 <- data %>% group_by_(block_id) %>%
      mutate(Treatment = sample(x = c(1:urns),
                                size = n(),
                                replace = T,
                                prob = p))
  }
}

df1 <- randomize(data = df, urns = J, block_id = "group", p = p, seed = 9782)

If I change replace = T to replace = F I get the following error:

Error: cannot take a sample larger than the population when 'replace = FALSE'

Clarification of my objective:

Suppose that I have 10 classrooms (or villages, or something like that). To keep it simple, suppose each classroom has 20 students (in reality they will have N_j). Classroom per classroom, I want to assign each student to one of J groups, for example J=3. P says the fraction that will be assigned to each group. For example 25% to group 1 40% to group 2 and 35% to group 3.

Body:
My answer to your other question is without replacement, as can be seen below:

block_rand <-  as.tibble(randomizr::block_ra(blocks = df$group, conditions = c("urn_1","urn_2","urn_3")))

df2 <- as.tibble(bind_cols(df, block_rand))

df2 %>% janitor::tabyl(group, value)

df2 %>%
  group_by(id) %>%
  filter(n()>1) %>%
  str()


问:
Add Mesh to Forge Viewer Scene
I use Forge Viewer v7.12. and I can't add THREE.Mesh to viewer scene. This is not function from version 7.3. How can I add custom geometry (Box, Surface, Line) to Scene?
And console writes this error: .WebGL-0x7f884f0a5400]GL ERROR :GL_INVALID_OPERATION : glDrawElements: buffer format and fragment output variable type incompatible.
Thanks</p>

答:
The recommended approach is to use an overlay instead of scene or sceneAfter, like this...

```<code>var geom = new THREE.SphereGeometry(10, 8, 8);
var material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
var sphereMesh = new THREE.Mesh(geom, material);
sphereMesh.position.set(1, 2, 3);

viewer.overlays.addMesh(sphereMesh, 'custom-scene');
</code>```

For more details, follow the example here:
https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/advanced_options/custom-geometry/

Title: Add Mesh to Forge Viewer Scene

Body:
The recommended approach is to use an overlay instead of scene or sceneAfter, like this...

var geom = new THREE.SphereGeometry(10, 8, 8);
var material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
var sphereMesh = new THREE.Mesh(geom, material);
sphereMesh.position.set(1, 2, 3);

viewer.overlays.addMesh(sphereMesh, 'custom-scene');

For more details, follow the example here:
https://forge.autodesk.com/en/docs/viewer/v7/developers_guide/advanced_options/custom-geometry/


问:
Expansion-panel from material angular 4
I hava an angular 4.4.4 application with material 2.0.0-beta.12 and I want to use the mat-expansion-panel from material design.

This is my code :

```<code>           <mat-expansion-panel class="parametersPanel">
                    <mat-expansion-panel-header>
                        <mat-panel-title>
                            PARAMETERS
                        </mat-panel-title>
                    </mat-expansion-panel-header>
                    <table style="width:100%">
                        <tbody>
                            <tr class="parameterListItem">
                                <td class="icon"><img src="assets/images/alert.png"></td>
                                <td class="parameterName">Parameter 1</td>
                                <td class="parameterValue">Value</td>
                                <td class="unit">unit</td>
                            </tr>
                        </tbody>
                    </table>
            </mat-expansion-panel>
</code>```

So it works well but it possible to remove the margin in the mat-expansion-panel-body which has, from the browser margin: 0 24px 16px; ?

答:
This code below will work when added to your components css file</p>

```<code>:host {
  ::ng-deep {
    .mat-expansion-panel-spacing {
      margin: 0px 0 !important;
    }
  }
}
</code>```

Title: Expansion-panel from material angular 4

Body:
I hava an angular 4.4.4 application with material 2.0.0-beta.12 and I want to use the mat-expansion-panel from material design.

This is my code :

           <mat-expansion-panel class="parametersPanel">
                    <mat-expansion-panel-header>
                        <mat-panel-title>
                            PARAMETERS
                        </mat-panel-title>
                    </mat-expansion-panel-header>

                                Parameter 1
                                Value
                                unit

            </mat-expansion-panel>

So it works well but it possible to remove the margin in the mat-expansion-panel-body which has, from the browser margin: 0 24px 16px; ?

Body:
This code below will work when added to your components css file

:host {
  ::ng-deep {
    .mat-expansion-panel-spacing {
      margin: 0px 0 !important;
    }
  }
}


问:
pandas groupby column and check if group meets multiple conditions
I have a DataFrame that looks like the following:

```<code>      X       Y      Date       are_equal
0   50.0    10.0  2018-08-19      False
1    NaN    10.0  2018-08-19      False
2    NaN    50.0  2018-08-19       True
3   10.0     NaN  2018-08-21      False
4    1.0     NaN  2018-08-19      False
5    NaN    10.0  2018-08-22      False
6   10.0     NaN  2018-08-21      False
</code>```

The are_equal column indicates that a value in Y is in X for the same date (in this case 50.0).

I am trying to group by date and find whether X contains a specific value (say 1.0) for a date that contains are_equal True.

My approach was to use df.iterrows() and get the row at next index after meeting the condition df['are_equal'] == True. However, the rows aren't necessarily ordered.

How can I group by Date and check if a date contains True in are_equal and 1.0 in column X for that same date?

The output I'm trying to achieve is a new Boolean column that looks like this:

```<code>   contains_specific_value
0    False
1    False
2    False
3    False
4    True
5    False
6    False
</code>```

答:
Let us do apply, this can add more condition but slow. You can check the other solution from transform

```<code>df['New']=df.groupby('Date').apply(lambda x : (x['X']==1)&x['are_equal'].any()).reset_index(level=0,drop=True)
df
Out[101]:
      X     Y        Date  are_equal    New
0  50.0  10.0  2018-08-19      False  False
1   NaN  10.0  2018-08-19      False  False
2   NaN  50.0  2018-08-19       True  False
3  10.0   NaN  2018-08-21      False  False
4   1.0   NaN  2018-08-19      False   True
5   NaN  10.0  2018-08-22      False  False
6  10.0   NaN  2018-08-21      False  False
</code>```

Or transform

```<code>df['X'].eq(1)&(df.groupby('Date').X.transform('any'))
Out[102]:
0    False
1    False
2    False
3    False
4     True
5    False
6    False
Name: X, dtype: bool
</code>```

Body:
I have a DataFrame that looks like the following:

      X       Y      Date       are_equal
0   50.0    10.0  2018-08-19      False
1    NaN    10.0  2018-08-19      False
2    NaN    50.0  2018-08-19       True
3   10.0     NaN  2018-08-21      False
4    1.0     NaN  2018-08-19      False
5    NaN    10.0  2018-08-22      False
6   10.0     NaN  2018-08-21      False

The are_equal column indicates that a value in Y is in X for the same date (in this case 50.0).

I am trying to group by date and find whether X contains a specific value (say 1.0) for a date that contains are_equal True.

My approach was to use df.iterrows() and get the row at next index after meeting the condition df['are_equal'] == True. However, the rows aren't necessarily ordered.

How can I group by Date and check if a date contains True in are_equal and 1.0 in column X for that same date?

The output I'm trying to achieve is a new Boolean column that looks like this:

   contains_specific_value
0    False
1    False
2    False
3    False
4    True
5    False
6    False

Body:
Let us do apply, this can add more condition but slow. You can check the other solution from transform

df['New']=df.groupby('Date').apply(lambda x : (x['X']==1)&x['are_equal'].any()).reset_index(level=0,drop=True)
df
Out[101]:
      X     Y        Date  are_equal    New
0  50.0  10.0  2018-08-19      False  False
1   NaN  10.0  2018-08-19      False  False
2   NaN  50.0  2018-08-19       True  False
3  10.0   NaN  2018-08-21      False  False
4   1.0   NaN  2018-08-19      False   True
5   NaN  10.0  2018-08-22      False  False
6  10.0   NaN  2018-08-21      False  False

Or transform

df['X'].eq(1)&(df.groupby('Date').X.transform('any'))
Out[102]:
0    False
1    False
2    False
3    False
4     True
5    False
6    False
Name: X, dtype: bool


问:
Moving text to new line with fetching data from firebase
I have a website that shows results from firebase.
I'm displaying data in a table, and showing the data in td tags.
Here's how I fetch my data:

```<code>var database = firebase.database();

      database.ref('box-label').once('value', function(snapshot) {
        if (snapshot.exists()) {
          var content = '';
          snapshot.forEach(function(data) {
            var val = data.val();
            content += '<td>' + val.brand + '</td>';
            content += '<td>' + val.style + '</td>';
            content += '<td>' + val.color + '</td>';
            content += '<td>' + val.ponumber + '</td>';
            content += '<td>' + val.color + '</td>';
            content += '<td>' + val.xs + '</td>';
            content += '<td>' + val.sm + '</td>';
            content += '<td>' + val.md + '</td>';
            content += '<td>' + val.lg + '</td>';
            content += '<td>' + val.xl + '</td>';
            content += '<td>' + val.xxl + '</td>';
            content += '<td>' + val.xxxl + '</td>';
            content += '<td>' + val.onesize + '</td>';
            content += '<td>' + val.ponumber + '</td>';
            content += '<td>' + val.totalunits + '</td>';
            content += '<td>' + val.boxnumber + '</td>';
            content += '<td>' + val.totalboxes + '</td>';
            content += '<td> ' + val.boxweight + '</td>';

          });
          $('#the__carton__results').append(content);
        }
      });
</code>```

This works out well, with one entry from the firebase, however if there's more than one firebase entry, the layout breaks.
For example: This is with 2 entries
The first entry ends with Mikk7, and I'd like to show the next entries on the next line, so it aligns right.

My styling for the table looks like this:

```<code>  tr#the__carton__results__table{
      font-size: 9px;
      font-weight: 900;
      font-family: Helvetica;
      text-align: center;
  }

  tr#the__carton__results{
      font-size: 9px;
      font-weight: 900;
      font-family: Helvetica;
      text-align: center;
  }
</code>```

答:
You're constantly adding cells to the same row in the table. So that means you end up with a single row for all products.

What you probably want is to generate a new row for each product:

```<code>var database = firebase.database();

database.ref('box-label').once('value', function(snapshot) {
  var content = '';
  snapshot.forEach(function(data) {
    content += '<tr>';
    var val = data.val();
    content += '<td>' + val.brand + '</td>';
    content += '<td>' + val.style + '</td>';
    content += '<td>' + val.color + '</td>';
    content += '<td>' + val.ponumber + '</td>';
    content += '<td>' + val.color + '</td>';
    content += '<td>' + val.xs + '</td>';
    content += '<td>' + val.sm + '</td>';
    content += '<td>' + val.md + '</td>';
    content += '<td>' + val.lg + '</td>';
    content += '<td>' + val.xl + '</td>';
    content += '<td>' + val.xxl + '</td>';
    content += '<td>' + val.xxxl + '</td>';
    content += '<td>' + val.onesize + '</td>';
    content += '<td>' + val.ponumber + '</td>';
    content += '<td>' + val.totalunits + '</td>';
    content += '<td>' + val.boxnumber + '</td>';
    content += '<td>' + val.totalboxes + '</td>';
    content += '<td> ' + val.boxweight + '</td>';
    content += '</tr>';

  });
  $('#the__carton__results').parent().append(content);
});
</code>```

Body:
I have a website that shows results from firebase.
I'm displaying data in a table, and showing the data in td tags.
Here's how I fetch my data:

var database = firebase.database();

      database.ref('box-label').once('value', function(snapshot) {
        if (snapshot.exists()) {
          var content = '';
          snapshot.forEach(function(data) {
            var val = data.val();
            content += '' + val.brand + '	';
            content += '' + val.style + '	';
            content += '' + val.color + '	';
            content += '' + val.ponumber + '	';
            content += '' + val.color + '	';
            content += '' + val.xs + '	';
            content += '' + val.sm + '	';
            content += '' + val.md + '	';
            content += '' + val.lg + '	';
            content += '' + val.xl + '	';
            content += '' + val.xxl + '	';
            content += '' + val.xxxl + '	';
            content += '' + val.onesize + '	';
            content += '' + val.ponumber + '	';
            content += '' + val.totalunits + '	';
            content += '' + val.boxnumber + '	';
            content += '' + val.totalboxes + '	';
            content += ' ' + val.boxweight + '	';

          });
          $('#the__carton__results').append(content);
        }
      });

This works out well, with one entry from the firebase, however if there's more than one firebase entry, the layout breaks.
For example: This is with 2 entries
The first entry ends with Mikk7, and I'd like to show the next entries on the next line, so it aligns right.

My styling for the table looks like this:

  tr#the__carton__results__table{
      font-size: 9px;
      font-weight: 900;
      font-family: Helvetica;
      text-align: center;
  }

  tr#the__carton__results{
      font-size: 9px;
      font-weight: 900;
      font-family: Helvetica;
      text-align: center;
  }

Body:
You're constantly adding cells to the same row in the table. So that means you end up with a single row for all products.

What you probably want is to generate a new row for each product:

var database = firebase.database();

database.ref('box-label').once('value', function(snapshot) {
  var content = '';
  snapshot.forEach(function(data) {
    content += '<tr>';
    var val = data.val();
    content += '<td>' + val.brand + '</td>';
    content += '<td>' + val.style + '</td>';
    content += '<td>' + val.color + '</td>';
    content += '<td>' + val.ponumber + '</td>';
    content += '<td>' + val.color + '</td>';
    content += '<td>' + val.xs + '</td>';
    content += '<td>' + val.sm + '</td>';
    content += '<td>' + val.md + '</td>';
    content += '<td>' + val.lg + '</td>';
    content += '<td>' + val.xl + '</td>';
    content += '<td>' + val.xxl + '</td>';
    content += '<td>' + val.xxxl + '</td>';
    content += '<td>' + val.onesize + '</td>';
    content += '<td>' + val.ponumber + '</td>';
    content += '<td>' + val.totalunits + '</td>';
    content += '<td>' + val.boxnumber + '</td>';
    content += '<td>' + val.totalboxes + '</td>';
    content += '<td> ' + val.boxweight + '</td>';
    content += '</tr>';

  });
  $('#the__carton__results').parent().append(content);
});


问:
how to align text and colons in straight line responsive
```<code> aaa       :111
 bbbbbbb   :22222
 cccccccccc:33333333
 dd        :44
 eeee      :5555
</code>```

<p>It should be responsive, I tried it but the text which is right side of colon is going below to the left side in mobile view. It is ok if the right side text is coming to right side when the screen size is reduced.please give me suggestions for my problem. </p>

答:
You can achieve it using table option in HTML. Please try below snippet:

table tbody tr td {
          text-align: left;
          vertical-align: middle;
        }

        table tbody tr td:nth-child(2):before {
          content: ":";
          display: inline-block;
          padding-left:10px;
          margin-right:10px;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table cellpadding="0" cellspacing="0">
    <tbody>
      <tr>
        <td>aaa</td>
        <td>111</td>
      </tr>
      <tr>
        <td>bbbbbbb</td>
        <td>22222</td>
      </tr>
      <tr>
        <td>cccccccccc</td>
        <td>33333333</td>
      </tr>
      <tr>
        <td>dd</td>
        <td>44</td>
      </tr>
      <tr>
        <td>eeee</td>
        <td>5555</td>
      </tr>
    </tbody>
  </table></code>```

Body:
 aaa       :111
 bbbbbbb   :22222
 cccccccccc:33333333
 dd        :44
 eeee      :5555

It should be responsive, I tried it but the text which is right side of colon is going below to the left side in mobile view. It is ok if the right side text is coming to right side when the screen size is reduced.please give me suggestions for my problem.

Body:
You can achieve it using table option in HTML. Please try below snippet:

table tbody tr td {
          text-align: left;
          vertical-align: middle;
        }

        table tbody tr td:nth-child(2):before {
          content: ":";
          display: inline-block;
          padding-left:10px;
          margin-right:10px;
        }

<table cellpadding="0" cellspacing="0">
    <tbody>
      <tr>
        <td>aaa</td>
        <td>111</td>
      </tr>
      <tr>
        <td>bbbbbbb</td>
        <td>22222</td>
      </tr>
      <tr>
        <td>cccccccccc</td>
        <td>33333333</td>
      </tr>
      <tr>
        <td>dd</td>
        <td>44</td>
      </tr>
      <tr>
        <td>eeee</td>
        <td>5555</td>
      </tr>
    </tbody>
  </table>


问:
Zoom/scale at mouse position
I am struggling to figure out and determine how to zoom on my mouse position based on this example. (https://stackblitz.com/edit/js-fxnmkm?file=index.js)

```<code>let node,
    scale = 1,
    posX = 0,
    posY = 0,
    node = document.querySelector('.frame');

const render = () => {
  window.requestAnimationFrame(() => {
    let val = `translate3D(${posX}px, ${posY}px, 0px) scale(${scale})`
    node.style.transform = val
  })
}

window.addEventListener('wheel', (e) => {
  e.preventDefault();

  // Zooming happens here
  if (e.ctrlKey) {
    scale -= e.deltaY * 0.01;
  } else {
    posX -= e.deltaX * 2;
    posY -= e.deltaY * 2;
  }

  render();
});
</code>```

My desired effect is based on this example (https://codepen.io/techslides/pen/zowLd?editors=0010) when zooming in. Currently my example above only scales to the center of the "viewport" but I want it to be where my cursor currently is.

I have searched high and low for a solution that is not implemented via canvas. Any help would be appreciated!

Caveat The reason why I am using the wheel event is to mimic the interaction of Figma (the design tool) panning and zooming.

答:
I think you need to use an external jquery plugin to achieve this:

js file :
https://ariutta.github.io/svg-pan-zoom/dist/svg-pan-zoom.js

working demo :
https://ariutta.github.io/svg-pan-zoom/

for more clarification please visit:
https://github.com/ariutta/svg-pan-zoom

Title: Zoom/scale at mouse position

Body:
I am struggling to figure out and determine how to zoom on my mouse position based on this example. (https://stackblitz.com/edit/js-fxnmkm?file=index.js)

let node,
    scale = 1,
    posX = 0,
    posY = 0,
    node = document.querySelector('.frame');

const render = () => {
  window.requestAnimationFrame(() => {
    let val = `translate3D(${posX}px, ${posY}px, 0px) scale(${scale})`
    node.style.transform = val
  })
}

window.addEventListener('wheel', (e) => {
  e.preventDefault();

  // Zooming happens here
  if (e.ctrlKey) {
    scale -= e.deltaY * 0.01;
  } else {
    posX -= e.deltaX * 2;
    posY -= e.deltaY * 2;
  }

  render();
});

My desired effect is based on this example (https://codepen.io/techslides/pen/zowLd?editors=0010) when zooming in. Currently my example above only scales to the center of the "viewport" but I want it to be where my cursor currently is.

I have searched high and low for a solution that is not implemented via canvas. Any help would be appreciated!

Caveat The reason why I am using the wheel event is to mimic the interaction of Figma (the design tool) panning and zooming.


问:
how to make animation inactive for some time period in jQuery
here the jsfiddle link to my problem http://jsfiddle.net/XnnvD/35/ (not quite working)

I'll try explaining what the problem is, I have 3 sets of animation in jQuery

1- Image bounces and fades away after  some TimePeriod as below:

```<code>$('#homePageImage').animate(
                    { top: '50px' },
                    { queue: false, duration: 1000, easing: 'easeOutBounce' });
$('#homePageImage').delay(3000).effect('drop', { direction: "right" });
</code>```

2- Set of images .fadeIn() randomly as below:

```<code>randNumArray = shuffle(randNumArray);
for (var i = 0; i < 9; i++)
{ $('#fs' + randNumArray[i]).delay(j += 200).fadeIn(j); }
</code>```

3- Hovering over these images, will enlarge them as below:

```<code>$(function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        });
</code>```

The Problem:
If the user hovers before the 1st set of animation is complete, the images don't .fadeIn() completely, and hence are partially/not visible

What I want:
I want the 3rd set (hovering to enlarge) to remain inactive till my 1st and 2nd set of animations are complete, how can I do this?

Thanks

答:
Don't you just want to use a callback:</p>

```<code>$('image').fadeIn('fast', function() {
  $('image').hover(function() {do stuff...});
});
</code>```

Body:
here the jsfiddle link to my problem http://jsfiddle.net/XnnvD/35/ (not quite working)

I'll try explaining what the problem is, I have 3 sets of animation in jQuery

1- Image bounces and fades away after  some TimePeriod as below:

$('#homePageImage').animate(
                    { top: '50px' },
                    { queue: false, duration: 1000, easing: 'easeOutBounce' });
$('#homePageImage').delay(3000).effect('drop', { direction: "right" });

2- Set of images .fadeIn() randomly as below:

randNumArray = shuffle(randNumArray);
for (var i = 0; i < 9; i++)
{ $('#fs' + randNumArray[i]).delay(j += 200).fadeIn(j); }

3- Hovering over these images, will enlarge them as below:

$(function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        });

The Problem:
If the user hovers before the 1st set of animation is complete, the images don't .fadeIn() completely, and hence are partially/not visible

What I want:
I want the 3rd set (hovering to enlarge) to remain inactive till my 1st and 2nd set of animations are complete, how can I do this?

Thanks

Body:
Don't you just want to use a callback:

$('image').fadeIn('fast', function() {
  $('image').hover(function() {do stuff...});
});


问:
BokehPass mix with other postprocessing THREE.js
I,m trying to put multiple passes in EffectComposer and everything is fine except for BokehPass.

My code look like this (I already got a scene, camera and renderer):

```<code>...

var renderPass = new THREE.RenderPass( scene, camera );

var postRenderer = new THREE.EffectComposer( renderer );

var copyPass = new THREE.ShaderPass( THREE.CopyShader );

var bokehSettings = {
    focus : 1.0, aperture : 0.025,  maxblur : 1.0,
    width: window.innerWidth, height : window.innerHeight
}

var bokehPass =  new THREE.BokehPass( scene, camera, bokehSettings );

var bleachPass = new THREE.ShaderPass( THREE.BleachBypassShader);//I make clone of uniforms but, for puspose, I don't write here.

postRenderer.addPass( renderPass );

postRenderer.addPass( bleachPass );

postRenderer.addPass( bokehPass );

postRenderer.addPass( copyPass );

...

function render(){

    postRenderer.render( 0.1 );

}

...
</code>```

The bleachPass work fine but not bokehPass in this order.

If I try : renderPass -> bleachPass -> bokehPass, bleachPass doesnt work.

Then I try : renderPass ->  bleachPass -> copyPass -> bokehPass, but it give me some weird result.

Someone know how to mix multiple passes with bokeh?

Thanks!

答:
Old question but for future reference here's the answer by @Mugen87:
https://github.com/mrdoob/three.js/issues/18634

BokehPass set needsSwap to false. That means the result of the buffer is not available in the read buffer for the subsequent post processing pass. This is done for performance reasons since usually this DOF pass is used on its own or at the end of the pass chain. So adding the following line of code should solve the issue:

```<code>bokehPass.needsSwap = true;
</code>```

Updated fiddle: https://jsfiddle.net/5nxy0tqp/

Body:
I,m trying to put multiple passes in EffectComposer and everything is fine except for BokehPass.

My code look like this (I already got a scene, camera and renderer):

...

var renderPass = new THREE.RenderPass( scene, camera );

var postRenderer = new THREE.EffectComposer( renderer );

var copyPass = new THREE.ShaderPass( THREE.CopyShader );

var bokehSettings = {
    focus : 1.0, aperture : 0.025,  maxblur : 1.0,
    width: window.innerWidth, height : window.innerHeight
}

var bokehPass =  new THREE.BokehPass( scene, camera, bokehSettings );

var bleachPass = new THREE.ShaderPass( THREE.BleachBypassShader);//I make clone of uniforms but, for puspose, I don't write here.

postRenderer.addPass( renderPass );

postRenderer.addPass( bleachPass );

postRenderer.addPass( bokehPass );

postRenderer.addPass( copyPass );

...

function render(){

    postRenderer.render( 0.1 );

}

...

The bleachPass work fine but not bokehPass in this order.

If I try : renderPass -> bleachPass -> bokehPass, bleachPass doesnt work.

Then I try : renderPass ->  bleachPass -> copyPass -> bokehPass, but it give me some weird result.

Someone know how to mix multiple passes with bokeh?

Thanks!

Body:
Old question but for future reference here's the answer by @Mugen87:
https://github.com/mrdoob/three.js/issues/18634

BokehPass set needsSwap to false. That means the result of the buffer is not available in the read buffer for the subsequent post processing pass. This is done for performance reasons since usually this DOF pass is used on its own or at the end of the pass chain. So adding the following line of code should solve the issue:

bokehPass.needsSwap = true;

Updated fiddle: https://jsfiddle.net/5nxy0tqp/


问:
Append Elements to DOM According to Values From JS Array
So the question's kind of weird but here's what I'm trying to accomplish:

I need a function that builds specific URLs, depending on an array inside a data attribute passed to the function, using a switch statement or whatever works best. This is my current syntax, which is probably wrong

const selectUrls = (args) => {
  const element = $("#element");

  for (let arg in args) {
    switch (arg) {
      case "facebook":
        element.append('Facebook');
        break;
      case "twitter":
        element.append('Twitter');
        break;
      default:
        console.log("error");
        break;
    }
  }
}
$(document).ready(function() {
  var services = $("#element").data("services");
  selectUrls(...[services]);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="element" data-services="['facebook','twitter']"></section></code>```

End-result should be:

index.html

```<code><section id="element" data-services="['facebook','twitter']">
    <a href="https://facebook.com">Facebook</a>
    <a href="https://twitter.com">Twitter</a>
</section>

...
</code>```

Obviously, if there's a better way to accomplish this, I'd be very open to trying it out.

Thanks!

答:
I done this...

const service_elm = document.querySelector('#element')

for (let service of service_elm.dataset.services.match(/\b(\w|')+\b/gim) )
  {
  let newA = document.createElement('a')
  newA.href = `https://${service}.com`
  newA.textContent = service.charAt(0).toUpperCase() + service.slice(1);
  service_elm.appendChild(newA)
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a { float:left; clear: both; margin:1em }</code>```

```

Body:
So the question's kind of weird but here's what I'm trying to accomplish:

I need a function that builds specific URLs, depending on an array inside a data attribute passed to the function, using a switch statement or whatever works best. This is my current syntax, which is probably wrong

const selectUrls = (args) => {
  const element = $("#element");

  for (let arg in args) {
    switch (arg) {
      case "facebook":
        element.append('Facebook');
        break;
      case "twitter":
        element.append('Twitter');
        break;
      default:
        console.log("error");
        break;
    }
  }
}
$(document).ready(function() {
  var services = $("#element").data("services");
  selectUrls(...[services]);
})

End-result should be:

index.html

    Facebook
    Twitter

...

Obviously, if there's a better way to accomplish this, I'd be very open to trying it out.

Thanks!

Body:
I done this...

const service_elm = document.querySelector('#element')

for (let service of service_elm.dataset.services.match(/\b(\w|')+\b/gim) )
  {
  let newA = document.createElement('a')
  newA.href = `https://${service}.com`
  newA.textContent = service.charAt(0).toUpperCase() + service.slice(1);
  service_elm.appendChild(newA)
  }

a { float:left; clear: both; margin:1em }

<section id="element" data-services="['facebook','twitter']"></section>


问:
Typescript / Type Safe Curried Functions
How to safely type curried functions in typescript?
With particular regard to the following example

interface Prop {
    <T, K extends keyof T>(name: K, object: T): T[K];
    <K>(name: K): <T>(object: T) => /* ?? */;
}

const prop: Prop = (key, object) => object[key];

const valid1 = prop('foo', { foo: 'hello' }); // string
const valid = prop('foo')({ foo: 'hello' });  // string

// `never`, since `baz` does not exist in { foo: string }
const invalid = prop('baz')({ foo: 'hello' }); // never
```

答:
Probably a bit verbose,
but does what it needs to:

interface Prop {
    <K extends PropertyKey, T extends {}>(name: K, object: T): K extends keyof T ? T[K] : undefined;
    <K extends PropertyKey>(name: K): <T extends {}>(object: T) => K extends keyof T ? T[K] : undefined;
}

declare const prop: Prop;

const invalid = prop('bar')({ foo: 'hello world' });
const valid = prop('foo')({ foo: 'hello world' });
const sLen = prop('length', 'Hello World');
const arity = prop('length')((a: number, b: number, c: number) => a + b + c);
```


问:
iPhone - scrolling a UISCrollview to keep objects moving
I have a UISCrollview. Inside this scroller I have a picture and over the picture I have some objects (as subviews of the picture), like layers in a Photoshop composition. So, if I zoom the picture, the objects will zoom. If I scroll the picture, the objects scroll.

Now consider this: I have the picture zoomed in. The picture is now larger than the iPad screen. I am seeing the top half of the picture. I touch an object that is over the picture and start dragging it to the bottom of the screen. My intent is to drop the dragged object at the bottom of the picture, but as the picture is zoomed in, I have to drag the element to bottom of the screen, release it, scroll the picture up and then continue dragging the object.

What I want is this: I start dragging and when I arrive at the boundary of the screen, the scroller starts scrolling automatically showing parts of the image that were down or up.

What do I need is to know the rect that is visible, a kind of inverse of scrollRectToVisible...

Considering that the picture can be zoomed at any level, how do I know if the element I am dragging is near the border. BTW, how do I know what part of the scroller is being shown, even if it is zoomed?

thanks.

答: The visible rectangle has a size of scrollView.bounds.size and an origin of scrollView.contentOffset, in the coordinate space of the scrollview. Depending on what exactly you are doing, you may need to use convertRect:fromView: or convertRect:toView: to convert it into the coordinate space of the zoomed view.


问:
How to seed data with CloudKit?
I need to create some records in CloudKit for each user when they start an app.

I can't just write a seed function that create records. Because when the user starts the app in two devices, they will each write their own seed record.

What I want instead is for the first device to write to CloudKit gets to create the record. And then second device will simply update the values of those records no recreate them.

How can I achieve this?

答:
You have a few options available to you, but all could potentially lead to race-conditions when attempting to write both at the same time, but the actuality of it happening is minimal.

No matter which approach is taken, you should always take the stance of query first. Check if the record exists, update it if needed, then write the new/updated values.

So, in your example:

The first app would query for the record, and create the record - because no record exists.

The second app to launch would query for the record, find it, then do nothing, because the record exists.

Each record in CloudKit maintains a modificationDate. So if you are really concerned about overwriting data that shouldn't be overridden, then you can add attentional queries and date checks to determine if the write should happen.

Title: How to seed data with CloudKit?


问:
Assessing the security of Docker in Kubernetes (+Rancher)
I have assessed the security configuration of Docker containers within a Kubernetes cluster using docker-bench. I have noted that all Kubernetes containers such as

```<code>kube-proxy
kubelet
kube-apiserver
k8s_kube-flannel_canal
k8s_POD_canal
k8s_trident-main_trident-csi
...
</code>```

run as root. Is this necessary?

Furthermore, some Kubernetes containers, such as k8s_trident-main_trident, kube-proxy and kubelet  ran in privileged mode. I guess this is necessary for Kubernetes to work properly.

My question is: how do you properly assess the security configuration of Docker in Kubernetes? I understand that most settings are covered by Kubernetes, such as CPU/memory usage, PID cgroup limit and health checks. However, now I don't know if I can say anything about the security configuration of Docker when it's managed through Kubernetes and Rancher (RancherOS is also used). Reframing the previous question: what are steps/controls that should be taken to harden Docker in addition to hardening Kubernetes?

答:
...run as root. Is this necessary?

If some of them do, you can assume there should be quite a good reason for that. I believe that creators of kubernetes are quite familiar with the concept of least privilege principle. So I would say: yes, most probably it is necessary to be able to perform required operations on the node system. However it can be discussed as for example here.

Does e.g. kubeadm really need root privileges ? Well... to be able to perform all the required operations, yes. Compare with this answer.

However ideas about running the whole kubernetes cluster as non-root user also arise. I found an interesting presentation discussing this concept.

You touched really broad topic in your question and it is impossible to provide a single proper answer. I would say it's rather material for an extensive blog article or even e book (compare with this one).

Furthermore, some Kubernetes containers, such as
  k8s_trident-main_trident, kube-proxy and kubelet ran in
  privileged mode. I guess this is necessary for Kubernetes to work
  properly.

If you want your containers to be able to perform also certain operations on host system, privileged mode cannot be avoided.

You may also want to familiarize with the following articles in official kubernetes documentation:

https://kubernetes.io/docs/concepts/security/overview/

https://kubernetes.io/docs/tasks/administer-cluster/securing-a-cluster/

I hope it helps.

Body:
I have assessed the security configuration of Docker containers within a Kubernetes cluster using docker-bench. I have noted that all Kubernetes containers such as

kube-proxy
kubelet
kube-apiserver
k8s_kube-flannel_canal
k8s_POD_canal
k8s_trident-main_trident-csi
...

run as root. Is this necessary?

Furthermore, some Kubernetes containers, such as k8s_trident-main_trident, kube-proxy and kubelet  ran in privileged mode. I guess this is necessary for Kubernetes to work properly.

My question is: how do you properly assess the security configuration of Docker in Kubernetes? I understand that most settings are covered by Kubernetes, such as CPU/memory usage, PID cgroup limit and health checks. However, now I don't know if I can say anything about the security configuration of Docker when it's managed through Kubernetes and Rancher (RancherOS is also used). Reframing the previous question: what are steps/controls that should be taken to harden Docker in addition to hardening Kubernetes?


问:
How to get time difference Duration totals grouped by Name and when Value changes in certain way?
I'm looking for the Sum of time value differences between rows where Value was initially 1 and is now 0, grouped by Name.

Example data for a single Name, but there are many different Names in the real data.

```<code>+--------+---------------+---------------------+--------+
| RowNum |     Name      |      Timestamp      | Value  |
+--------+---------------+---------------------+--------+
|      1 | D1_HS_308_ALM | 2020-02-10 11:55:00 | 0      |
|      2 | D1_HS_308_ALM | 2020-02-10 11:51:00 | 0      |
|      3 | D1_HS_308_ALM | 2020-02-10 11:49:00 | NULL   |
|      4 | D1_HS_308_ALM | 2020-02-10 11:46:00 | 1      |
|      5 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      6 | D1_HS_308_ALM | 2020-02-10 08:02:00 | NULL   |
|      7 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      8 | D1_HS_308_ALM | 2020-02-10 07:56:00 | 1      |
|      9 | D1_HS_308_ALM | 2020-02-10 07:51:00 | 1      |
|     10 | D1_HS_308_ALM | 2020-02-10 07:50:00 | 0      |
+--------+---------------+---------------------+--------+
</code>```

This data should return 11 minutes for Row 9-->7 transition and 5 minutes for Row 4-->2 transition; totaling 16 minutes for this Name.

I'm not sure how to accomplish this when it's not guaranteed that the next row has the correct Value change - sometimes it will be several or many rows later.

答:
Just modified the select query by Cetin as per your need:</p>

```<code>DECLARE @myTable TABLE
(
    RowNum INT,
    Name VARCHAR(20),
    [Timestamp] DATETIME,
    Value INT
);

INSERT INTO @myTable
(
    RowNum,
    Name,
    [Timestamp],
    Value
)
VALUES
(1, 'D1_HS_308_ALM', '2020-02-10 11:55:00', 0),
(2, 'D1_HS_308_ALM', '2020-02-10 11:51:00', 0),
(3, 'D1_HS_308_ALM', '2020-02-10 11:49:00', NULL),
(4, 'D1_HS_308_ALM', '2020-02-10 11:46:00', 1),
(5, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(6, 'D1_HS_308_ALM', '2020-02-10 08:02:00', NULL),
(7, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(8, 'D1_HS_308_ALM', '2020-02-10 07:56:00', 1),
(9, 'D1_HS_308_ALM', '2020-02-10 07:51:00', 1),
(10, 'D1_HS_308_ALM', '2020-02-10 07:50:00', 0);

SELECT tmp.Name,
       SUM(DATEDIFF(MINUTE, tStart, tEnd)) AS duration
FROM
(
    SELECT t1.Name,
           --MIN(t1.RowNum) AS rStart,
           MIN(t1.Timestamp) AS tStart,
           --t.rNo AS rEnd,
           t.tEnd
    FROM @myTable t1
        OUTER APPLY
    (
        SELECT TOP (1)
               --t2.RowNum,
               t2.Timestamp
        FROM @myTable t2
        WHERE t1.Name = t2.Name
              AND t2.Timestamp > t1.Timestamp
              AND t2.Value = 0
        ORDER BY t2.Timestamp
    --) t(rNo, tEnd)
    ) t(tEnd)
    WHERE t1.Value = 1
    GROUP BY t1.Name,
             --t.rNo,
             t.tEnd
) tmp
GROUP BY tmp.Name;
</code>```

Body:
I'm looking for the Sum of time value differences between rows where Value was initially 1 and is now 0, grouped by Name.

Example data for a single Name, but there are many different Names in the real data.

+--------+---------------+---------------------+--------+
| RowNum |     Name      |      Timestamp      | Value  |
+--------+---------------+---------------------+--------+
|      1 | D1_HS_308_ALM | 2020-02-10 11:55:00 | 0      |
|      2 | D1_HS_308_ALM | 2020-02-10 11:51:00 | 0      |
|      3 | D1_HS_308_ALM | 2020-02-10 11:49:00 | NULL   |
|      4 | D1_HS_308_ALM | 2020-02-10 11:46:00 | 1      |
|      5 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      6 | D1_HS_308_ALM | 2020-02-10 08:02:00 | NULL   |
|      7 | D1_HS_308_ALM | 2020-02-10 08:02:00 | 0      |
|      8 | D1_HS_308_ALM | 2020-02-10 07:56:00 | 1      |
|      9 | D1_HS_308_ALM | 2020-02-10 07:51:00 | 1      |
|     10 | D1_HS_308_ALM | 2020-02-10 07:50:00 | 0      |
+--------+---------------+---------------------+--------+

This data should return 11 minutes for Row 9-->7 transition and 5 minutes for Row 4-->2 transition; totaling 16 minutes for this Name.

I'm not sure how to accomplish this when it's not guaranteed that the next row has the correct Value change - sometimes it will be several or many rows later.

Body:
Just modified the select query by Cetin as per your need:

DECLARE @myTable TABLE
(
    RowNum INT,
    Name VARCHAR(20),
    [Timestamp] DATETIME,
    Value INT
);

INSERT INTO @myTable
(
    RowNum,
    Name,
    [Timestamp],
    Value
)
VALUES
(1, 'D1_HS_308_ALM', '2020-02-10 11:55:00', 0),
(2, 'D1_HS_308_ALM', '2020-02-10 11:51:00', 0),
(3, 'D1_HS_308_ALM', '2020-02-10 11:49:00', NULL),
(4, 'D1_HS_308_ALM', '2020-02-10 11:46:00', 1),
(5, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(6, 'D1_HS_308_ALM', '2020-02-10 08:02:00', NULL),
(7, 'D1_HS_308_ALM', '2020-02-10 08:02:00', 0),
(8, 'D1_HS_308_ALM', '2020-02-10 07:56:00', 1),
(9, 'D1_HS_308_ALM', '2020-02-10 07:51:00', 1),
(10, 'D1_HS_308_ALM', '2020-02-10 07:50:00', 0);

SELECT tmp.Name,
       SUM(DATEDIFF(MINUTE, tStart, tEnd)) AS duration
FROM
(
    SELECT t1.Name,
           --MIN(t1.RowNum) AS rStart,
           MIN(t1.Timestamp) AS tStart,
           --t.rNo AS rEnd,
           t.tEnd
    FROM @myTable t1
        OUTER APPLY
    (
        SELECT TOP (1)
               --t2.RowNum,
               t2.Timestamp
        FROM @myTable t2
        WHERE t1.Name = t2.Name
              AND t2.Timestamp > t1.Timestamp
              AND t2.Value = 0
        ORDER BY t2.Timestamp
    --) t(rNo, tEnd)
    ) t(tEnd)
    WHERE t1.Value = 1
    GROUP BY t1.Name,
             --t.rNo,
             t.tEnd
) tmp
GROUP BY tmp.Name;


问:
How. if possible, do I create *.jsxbin (export to binary) for jsx ExtendScript files using Visual Studio Community 2019
At present I use ExtendScript Toolkit from Adobe in Windows to only generate the jsxbin file from the jsx files I code using Visual Studio Community 2019 (not VS Code!).  I also handle my C++ Photoshop plugin code and building in VS2019.  I'm aware that I can edit and create the jsx/jsxbin files in VSCode but would like to stay with VS2019 for everything.  If I could easily transfer the build of C++ for the plugin to VSCode I might do that.  I have not found anything about how to do that.

I was told that I could use this Convert jsx ExtendScript files into jsxbin files using ExtendScript Toolkit  but I have no idea how to use it.  I can't get the person who told me about it to help and I can't find contact info for the author.

I appreciate your patience for my running on.

RONC

答:
You can create a temporary js script and run it with ESTK.
It's easier if you're using a build tool such as Gulp/ Grunt/ Webpack.

Here's a basic sample for a Gulp task on Windows, using NodeJS:

```<code>const exec = require('child_process').exec;
const path = require('path');
const fs = require('fs');
const del = require('del');
const log = require('gutil-color-log'); // OPTIONAL

var myJSFilePath = 'PATH\\TO\\MY\\JS\\FILE.jsx';

exports.encodeToJSXBIN = toJSXBIN;

function toJSXBIN (done)
{
  var jsxbinFilePath = path.join(path.dirname(myJSFilePath), path.parse(myJSFilePath).name + '.jsxbin'), // Will be written in the same folder as your .jsx file
  compilerScriptPath = path.join('FOLDER\\PATH\\TO\\TEMPORARY\\SCRIPT', 'compiler.jsx'),
  estkPath = "PATH\\TO\\ExtendScript Toolkit.exe", // Could be: C:\\Program Files (x86)\\Adobe\\Adobe ExtendScript Toolkit CC\\ExtendScript Toolkit.exe
  estkCommand = JSON.stringify(estkPath) + ' -cmd ' + JSON.stringify(compilerScriptPath),
  compilerScript = "#target estoolkit#dbg\n" +
  "\n" +
  "var jsxbinContent, jsxbinFile;\n" +
  "\n" +
  "jsxbinContent = app.compile(" + JSON.stringify(fs.readFileSync(myJSFilePath, 'utf8')) + ");\n" +
  "jsxbinFile = File(" + JSON.stringify(jsxbinFilePath) + ");\n" +
  "jsxbinFile.open(\"w\");\n" +
  "jsxbinFile.write(jsxbinContent);\n" +
  "jsxbinFile.close();";

  fs.writeFileSync(compilerScriptPath, compilerScript);

  exec(estkCommand, (err, stdoutA, stderrA) =>
  {
    if (err)
    {
      log('red', err.toString()); // OPTIONAL
      done();
    }

    del([compilerScriptPath], {force: true}); // Remove the temporary compiler.jsx file

    /*
    - OPTIONAL step
    - single line .jsxbin file
    - you can also replace .jsxbin extension with .jsx if you want
    */
    fs.writeFileSync(jsxbinFilePath, fs.readFileSync(jsxbinFilePath, 'utf8').replace(/[\r\n]+/gm, ''));

    done();
  });
}
</code>```

EDIT #1:

Until you'll familiarize yourself with NodeJS and Gulp or any other build tool, I've made a quick setup you can use.

Install NodeJS: https://nodejs.org/en/

Open a CMD/ Terminal/ GitBash ( https://git-scm.com/downloads ) in the "Export_to_JSXBIN" sample folder.

Install Gulp globally: npm install -g gulp

Then: npm install

Put your .jsx/ .js files you want to encode into 'jsx_sources'

From the command line type: gulp encodeJS

A new folder 'jsx_encoded' will be created which will contain the .jsxbin files with the extension changed to .jsx and all the content formatted to a single line.

You can of course leave the extension unchanged and write the encoded JS in the same folder as your source file, if that suits your needs.

The content of 'gulpfile.js' should be easy to understand.

Ooh... and check the ESTK path (var estkPath), especially if you're on a mac.

Export_to_JSXBIN Gulp sample: https://url.io/export_to_jsxbin

Gulp tasks can be launched from your IDE too. I'm sure you can find an extension for this.

Body:
You can create a temporary js script and run it with ESTK.
It's easier if you're using a build tool such as Gulp/ Grunt/ Webpack.

Here's a basic sample for a Gulp task on Windows, using NodeJS:

const exec = require('child_process').exec;
const path = require('path');
const fs = require('fs');
const del = require('del');
const log = require('gutil-color-log'); // OPTIONAL

var myJSFilePath = 'PATH\\TO\\MY\\JS\\FILE.jsx';

exports.encodeToJSXBIN = toJSXBIN;

function toJSXBIN (done)
{
  var jsxbinFilePath = path.join(path.dirname(myJSFilePath), path.parse(myJSFilePath).name + '.jsxbin'), // Will be written in the same folder as your .jsx file
  compilerScriptPath = path.join('FOLDER\\PATH\\TO\\TEMPORARY\\SCRIPT', 'compiler.jsx'),
  estkPath = "PATH\\TO\\ExtendScript Toolkit.exe", // Could be: C:\\Program Files (x86)\\Adobe\\Adobe ExtendScript Toolkit CC\\ExtendScript Toolkit.exe
  estkCommand = JSON.stringify(estkPath) + ' -cmd ' + JSON.stringify(compilerScriptPath),
  compilerScript = "#target estoolkit#dbg\n" +
  "\n" +
  "var jsxbinContent, jsxbinFile;\n" +
  "\n" +
  "jsxbinContent = app.compile(" + JSON.stringify(fs.readFileSync(myJSFilePath, 'utf8')) + ");\n" +
  "jsxbinFile = File(" + JSON.stringify(jsxbinFilePath) + ");\n" +
  "jsxbinFile.open(\"w\");\n" +
  "jsxbinFile.write(jsxbinContent);\n" +
  "jsxbinFile.close();";

  fs.writeFileSync(compilerScriptPath, compilerScript);

  exec(estkCommand, (err, stdoutA, stderrA) =>
  {
    if (err)
    {
      log('red', err.toString()); // OPTIONAL
      done();
    }

    del([compilerScriptPath], {force: true}); // Remove the temporary compiler.jsx file

    /*
    - OPTIONAL step
    - single line .jsxbin file
    - you can also replace .jsxbin extension with .jsx if you want
    */
    fs.writeFileSync(jsxbinFilePath, fs.readFileSync(jsxbinFilePath, 'utf8').replace(/[\r\n]+/gm, ''));

    done();
  });
}

EDIT #1:

Until you'll familiarize yourself with NodeJS and Gulp or any other build tool, I've made a quick setup you can use.

Install NodeJS: https://nodejs.org/en/

Open a CMD/ Terminal/ GitBash ( https://git-scm.com/downloads ) in the "Export_to_JSXBIN" sample folder.

Install Gulp globally: npm install -g gulp

Then: npm install

Put your .jsx/ .js files you want to encode into 'jsx_sources'

From the command line type: gulp encodeJS

A new folder 'jsx_encoded' will be created which will contain the .jsxbin files with the extension changed to .jsx and all the content formatted to a single line.

You can of course leave the extension unchanged and write the encoded JS in the same folder as your source file, if that suits your needs.

The content of 'gulpfile.js' should be easy to understand.

Ooh... and check the ESTK path (var estkPath), especially if you're on a mac.

Export_to_JSXBIN Gulp sample: https://url.io/export_to_jsxbin

Gulp tasks can be launched from your IDE too. I'm sure you can find an extension for this.


问:
CORS error when serving angular with express
I have 2 server.js files. One of them is inside the backend folder where when I run nodemon server.js  on localhost:3000. And I'll start angular with ng serve inside the angular folder and login to my app no problem. Everything works. No CORS issue.

BUT

If I try to run my server.js file in the root directory where express serves my angular build folder. It starts up on localhost:8080, but when I try to login to my app, I get

inside my app.js file I have the following, which should be relevant.  Another thing worth noting
 is I made a docker version and that version gives me the CORS error too. So it seems to only work when running locally with ng serve and nodemon server.js

```<code>app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );

  next();
});

</code>```

server.js file in backend folder (localhost:3000 No CORS error)

```<code>const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});
</code>```

server.js in root directory (localhost:8080 CORS error)

```<code>var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
const userRoutes = require("./app/routes/user");
const appRoutes = require("./app/app");

const cors = require("cors");
app.use(morgan('dev'));

app.use(cors({ origin: 'http://localhost:8080' , credentials :  true}));var mongoose   = require('mongoose');
var path       = require('path');
var config = 'mongodb://azure45:azure45@ds133321.mlab.com:33321/azure_chat'
//const app = require("./app");
const debug = require("debug")("node-angular");
var env = require("dotenv").config();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    next();
});

mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

app.use(express.static(__dirname + '/public/dist/glass/'));

//var apiRoutes = require('./app/app')(app, express);
app.use("/api/", appRoutes);
app.use("/api/user", userRoutes);

app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/dist/glass/index.html'));
});

app.listen(8080);
console.log('Magic happens on port ' + 8080);

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

</code>```

Here's the project file structure as a reference. app.js is where all my APIs are.

答:
With reference to rise's answer:
Add options to cors method:

```<code>var corsOptions = {
origin: 'your client url',
optionsSuccessStatus: 200,
</code>```

}
    app.use(cors(corsOptions));

Body:
I have 2 server.js files. One of them is inside the backend folder where when I run nodemon server.js  on localhost:3000. And I'll start angular with ng serve inside the angular folder and login to my app no problem. Everything works. No CORS issue.

BUT

If I try to run my server.js file in the root directory where express serves my angular build folder. It starts up on localhost:8080, but when I try to login to my app, I get

inside my app.js file I have the following, which should be relevant.  Another thing worth noting
 is I made a docker version and that version gives me the CORS error too. So it seems to only work when running locally with ng serve and nodemon server.js

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );

  next();
});

server.js file in backend folder (localhost:3000 No CORS error)

const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});

server.js in root directory (localhost:8080 CORS error)

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
const userRoutes = require("./app/routes/user");
const appRoutes = require("./app/app");

const cors = require("cors");
app.use(morgan('dev'));

app.use(cors({ origin: 'http://localhost:8080' , credentials :  true}));var mongoose   = require('mongoose');
var path       = require('path');
var config = 'mongodb://azure45:azure45@ds133321.mlab.com:33321/azure_chat'
//const app = require("./app");
const debug = require("debug")("node-angular");
var env = require("dotenv").config();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    next();
});

mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

app.use(express.static(__dirname + '/public/dist/glass/'));

//var apiRoutes = require('./app/app')(app, express);
app.use("/api/", appRoutes);
app.use("/api/user", userRoutes);

app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/dist/glass/index.html'));
});

app.listen(8080);
console.log('Magic happens on port ' + 8080);

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

Here's the project file structure as a reference. app.js is where all my APIs are.

Body:
With reference to rise's answer:
Add options to cors method:

var corsOptions = {
origin: 'your client url',
optionsSuccessStatus: 200,

}
    app.use(cors(corsOptions));