问:
Applying a function to each couple of elements of a column in a pandas data frame
I have the need to create a new column of a pandas data frame applying a function to each couple of consecutive elements.The first element if the new column has to be a nan.
Let's assume that the function is the sum of the elements divided by 3.
Here's an example to clarify what I need:

```<code>a b new_column
1 2 nan
3 4 2
5 5 3
</code>```

the operation is on column b:
first is nan, 2 = (2 + 4) / 3 == f(2,4), 3 = (4 + 5) / 3 == f(4,5)

Can anyone help me? Thank you really much

答:
I believe this solution should now give you the desired result:</p>
```<code># We are going to assign a new column
df = df.assign(
    # based on a function that we will apply
    new_column=df.apply(
        # If our row index is not 0: --> if row.name !=0
        # we take the value of column["b"] --> row["b]
        # we add the value located at the current row index -1 --> df["b"].iat[row.name -1]
        # then we divide by 3 without rest --> //3
        lambda row: (row["b"] + df["b"].iat[row.name - 1])//3 if row.name != 0 else "", axis=1
    )
)
</code>```

Body:
I have the need to create a new column of a pandas data frame applying a function to each couple of consecutive elements.The first element if the new column has to be a nan.
Let's assume that the function is the sum of the elements divided by 3.
Here's an example to clarify what I need:

a b new_column
1 2 nan
3 4 2
5 5 3

the operation is on column b:
first is nan, 2 = (2 + 4) / 3 == f(2,4), 3 = (4 + 5) / 3 == f(4,5)

Can anyone help me? Thank you really much

Body:
I believe this solution should now give you the desired result:

# We are going to assign a new column
df = df.assign(
    # based on a function that we will apply
    new_column=df.apply(
        # If our row index is not 0: --> if row.name !=0
        # we take the value of column["b"] --> row["b]
        # we add the value located at the current row index -1 --> df["b"].iat[row.name -1]
        # then we divide by 3 without rest --> //3
        lambda row: (row["b"] + df["b"].iat[row.name - 1])//3 if row.name != 0 else "", axis=1
    )
)


来源: stackexchange

问:
Is it possible to pull out a list of particular field values from a collection of generic objects in C#?
I have the following method in a class I am using for pagination in my app:

```<code>public static PagedList<T> ToPagedList(IEnumerable<T> source, int pageNumber, int pageSize)
        {
            var count = source.Count();
            var items = source
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize).ToList();

            return new PagedList<T>(items, count, pageNumber, pageSize);
        }
</code>```

In this method I am passing in a collection of generic objects as IEnumerable<T> source which regardless of type will always have an Id field. What I'd like to do is pull out all of the Ids for these objects and store them in a list to be passed into my PagedList constructor. Is this possible?

答:
Yes it is possible. You can use Reflection to get the value of a property.

```<code>item.GetType().GetProperty("Id").GetValue(item, null);
</code>```

Edit: Respond to @CoolBots' comment

In case Id is a field, you can use GetField instead of GetProperty

item.GetType().GetField("Id").GetValue(item, null);
```

but if the item doesn't have the "Id" property, this code will fail, so remember to check for null.

ContentLicense: CC BY-SA 4.0

Body:
I have the following method in a class I am using for pagination in my app:

public static PagedList<T> ToPagedList(IEnumerable<T> source, int pageNumber, int pageSize)
        {
            var count = source.Count();
            var items = source
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize).ToList();

            return new PagedList<T>(items, count, pageNumber, pageSize);
        }

In this method I am passing in a collection of generic objects as IEnumerable<T> source which regardless of type will always have an Id field. What I'd like to do is pull out all of the Ids for these objects and store them in a list to be passed into my PagedList constructor. Is this possible?

Body:
Yes it is possible. You can use Reflection to get the value of a property.

item.GetType().GetProperty("Id").GetValue(item, null);

Edit: Respond to @CoolBots' comment

In case Id is a field, you can use GetField instead of GetProperty

item.GetType().GetField("Id").GetValue(item, null);

but if the item doesn't have the "Id" property, this code will fail, so remember to check for null.


问:
Regex matching for or sembol
Hello I have a regex and its (^|\W)(t)|(t\W*year)($|\W)

my test case is

has to match

```<code>t-year
t
</code>```

doesnt match

```<code>test123
</code>```

but the problem for test123its matching it shouldn't match and also for t-year it is matching but only for t character
You can check from here https://regexr.com/6eqfi

答:
You might for example use

```<code>\bt(?:[^\w\s]year)?\b
</code>```

\b A word boundary to prevent a partial word match

t Match literally

(?:[^\w\s]year)? Optionally match a non word character except for a whitespace char

\b A word boundary

Regex demo

Title: Regex matching for or sembol

Body:
Hello I have a regex and its (^|\W)(t)|(t\W*year)($|\W)

my test case is

has to match

t-year
t

doesnt match

test123

but the problem for test123its matching it shouldn't match and also for t-year it is matching but only for t character
You can check from here https://regexr.com/6eqfi

Body:
You might for example use

\bt(?:[^\w\s]year)?\b

\b A word boundary to prevent a partial word match

t Match literally

(?:[^\w\s]year)? Optionally match a non word character except for a whitespace char

\b A word boundary

Regex demo


问:
Stack per two columns and two measures
I have data that looks something like this:

```<code>order_id     Product_A    Product_B    Price_Product_A    Price_Product_B
100          Pen          Notebook     1.5                3
101          Bag          Watch        10                 12
</code>```

I need it to look like this:

```<code>order_id    product    price
100         Pen        1.5
100         Notebook   3
101         Bag        10
101         Watch      12
</code>```

How can I use stack() and unstack() for this? I used it so fat only for one numeric measure.

答:
I would simply create two dataframes: one for product A and one for product B. Then set the column names for both and append them like this:

```<code>df1 = df[['order_id', 'Product_A', 'Price_Product_A']]
df2 = df[['order_id', 'Product_B', 'Price_Product_B']]

df1.columns = ['order_id', 'product', 'price']
df2.columns = ['order_id', 'product', 'price']

df = df1.append(df2)
df
</code>```

Output:

```<code>    order_id    product price
0   100 Pen       1.5
1   101 Bag       10.0
0   100 Notebook  3.0
1   101 Watch     12.0
</code>```

Title: Stack per two columns and two measures

Body:
I have data that looks something like this:

order_id     Product_A    Product_B    Price_Product_A    Price_Product_B
100          Pen          Notebook     1.5                3
101          Bag          Watch        10                 12

I need it to look like this:

order_id    product    price
100         Pen        1.5
100         Notebook   3
101         Bag        10
101         Watch      12

How can I use stack() and unstack() for this? I used it so fat only for one numeric measure.

Body:
I would simply create two dataframes: one for product A and one for product B. Then set the column names for both and append them like this:

df1 = df[['order_id', 'Product_A', 'Price_Product_A']]
df2 = df[['order_id', 'Product_B', 'Price_Product_B']]

df1.columns = ['order_id', 'product', 'price']
df2.columns = ['order_id', 'product', 'price']

df = df1.append(df2)
df

Output:

    order_id    product price
0   100 Pen       1.5
1   101 Bag       10.0
0   100 Notebook  3.0
1   101 Watch     12.0


问:
Post JSON data to Facebook
In the app, I want to post a photo, and some text. I am able to post if I am using local stored data in resources but when data (in JSON format) is coming from server at the run time, I am not able to post that image and text which is coming from server in the JSON format.

Is there any way to post data at the runtime or I have to store the data at the client side, but in that case, the app will be bulky because data could be different at different locations?

答: I am not sure but you may be asking about posting an image using a URL instead of assuming data is local. If so, see this blog post - https://developers.facebook.com/blog/post/526/ and it introduced the ability to post an image by passing in a "url" parameter through the Graph API.</p>

ContentLicense: CC BY-SA 3.0

Title: Post JSON data to Facebook


问:
Duplicating ScritableObjects with Values per Script Unity
I am making a Multiplayer Game with MLAPI. The problem is, i have a ability system so every ability get executed over an ScritableObject. The problem is, if i have for example five Players in the scene all Players are referenced to the same ScritableObject. And so when somebody execute a ability. The other players are also doing it.
So my Question is can I duplicate my default ability ScritableObject so that every player has its own abilities ScritableObject but with the same Values as the default ability ScritableObject. I must do that over Script.
I know i could create a new ScritableObject and then make a method who paste my values. But maybe somebody has a better idea??????????</p>

答:
Afaik you can use Instantiate also for cloning ScriptableObject on runtime! Only you can of course not use any component taking more then the original parameter (which makes sense).

And the same way as ScriptableObject.CreateInstance this will of course not create an asset but only a runtime instance.


问:
Python - Plotting histogram of a for loop for dice rolls
I am trying to plot a histogram for the sum of 20 dice rolls when the simulation is ran 1000 times.

```<code>def dice(n):
total = 0
for i in range(1000):
    total += random.randint(1, 6)
    plt.hist(total)
    plt.title('Outcome of 20 Rolls')
return total
</code>```

I would really appreciate some help. Thanks.

答:
```<code>import matplotlib.pyplot as plt
import random

def roll(n):
    outcomes = [random.randint(1, 6) for _ in range(n)]
    return sum(outcomes)

rolls = 20
simu = 1000
sums = [roll(rolls) for _ in range(simu)]

plt.hist(sums, bins=40)
plt.title(f"Sum of {rolls} rolls ({simu} times)")
</code>```

Body:
I am trying to plot a histogram for the sum of 20 dice rolls when the simulation is ran 1000 times.

def dice(n):
total = 0
for i in range(1000):
    total += random.randint(1, 6)
    plt.hist(total)
    plt.title('Outcome of 20 Rolls')
return total

I would really appreciate some help. Thanks.


问:
use nginx as reverse proxy for a docker container
I am new to using docker and nginx together so i apologize in advance for my simple question which I am unable to get an answer to despite going through many resources on youtube.

I created an ubuntu server and ran the following command

```<code>sudo apt install nginx
</code>```

Now I have a very simple flask application docker image(publicly available on docker hub and not developed by me) and I want to configure my nginx to work as a reverse proxy to my container running the said image.

My code for the reverse proxy in nginx configuration is as follows:

```<code>server{
    listen 80;
    location / {
        proxy_pass "http://192.168.0.20:8000"
    }
}
</code>```

192.168.0.20 is my server ip and 8000 is the host port over which i am forwarding my docker container like

```<code>docker container run -p 8000:5000 <image>
</code>```

But when I run http://192.168.0.20/ it opens default nginx index.html whereas I want it to forward to my app container to serve that static file because when i run http://192.168.0.20:8000/ it gives me desired output.

This might sound like a dumb question but i have been struggling to get a hang of nginx.

Thanks in advance for the help !!!

答:
To reach the host from inside the container, you can't use 192.168.0.20, since that address isn't known inside the container. Depending on your host OS, you can use 172.17.0.1 (Linux) or host.docker.internal (Windows). If your OS is Linux, you should change your config to

```<code>server {
    listen 80;
    location / {
        proxy_pass "http://172.17.0.1:8000/"
    }
}
</code>```

Rather than installing nginx yourself, you can use the nginx images that are available on docker hub. To get your config file into it, you copy it to /etc/nginx/conf.d/default.conf. Create a Dockerfile containing

```<code>FROM nginx
COPY nginx.conf /etc/nginx/conf.d/default.conf
</code>```

Build and run it with

```<code>docker build -t mynginx .
docker run -d -p 80:80 mynginx
</code>```

Now you should be able to go to http://192.168.0.20/ and get a response from the Flask app.

Body:
I am new to using docker and nginx together so i apologize in advance for my simple question which I am unable to get an answer to despite going through many resources on youtube.

I created an ubuntu server and ran the following command

sudo apt install nginx

Now I have a very simple flask application docker image(publicly available on docker hub and not developed by me) and I want to configure my nginx to work as a reverse proxy to my container running the said image.

My code for the reverse proxy in nginx configuration is as follows:

server{
    listen 80;
    location / {
        proxy_pass "http://192.168.0.20:8000"
    }
}

192.168.0.20 is my server ip and 8000 is the host port over which i am forwarding my docker container like

docker container run -p 8000:5000 <image>

But when I run http://192.168.0.20/ it opens default nginx index.html whereas I want it to forward to my app container to serve that static file because when i run http://192.168.0.20:8000/ it gives me desired output.

This might sound like a dumb question but i have been struggling to get a hang of nginx.

Thanks in advance for the help !!!

Body:
To reach the host from inside the container, you can't use 192.168.0.20, since that address isn't known inside the container. Depending on your host OS, you can use 172.17.0.1 (Linux) or host.docker.internal (Windows). If your OS is Linux, you should change your config to

server {
    listen 80;
    location / {
        proxy_pass "http://172.17.0.1:8000/"
    }
}

Rather than installing nginx yourself, you can use the nginx images that are available on docker hub. To get your config file into it, you copy it to /etc/nginx/conf.d/default.conf. Create a Dockerfile containing

FROM nginx
COPY nginx.conf /etc/nginx/conf.d/default.conf

Build and run it with

docker build -t mynginx .
docker run -d -p 80:80 mynginx

Now you should be able to go to http://192.168.0.20/ and get a response from the Flask app.


问:
Remote object handles in Protocol Buffers?
Does Protocol Buffers support remote object handles? Say to support an API like the following:

```<code>service RemoteObjectsDemo {
    rpc AllocateRemoteObject() returns (RemoteObjectHandle);
    rpc UseRemoteObject(RemoteObjectHandle) returns (something);
    rpc FreeRemoteObject(RemoteObjectHandle) returns (Empty);
}
</code>```

The point is that sometimes all you need is for some object to exist on the server, but there's not need to ever transfer that object across the wire.

答:
Because gRPC and protocol buffers are language|runtime agnostic and because there's no universal concept of an object handle, protocol buffers does not expose process-specific object references.

Also, in many cases, it's not possible to assume that there's a single process implementing the RPC; load-balancers or other scale-out mechanisms will direct traffic to one of many backend processes.

That said, gRPC servers can track "things" that represent shared resources (often e.g. database|service connections) and there's no reason why this couldn't also be used to share objects.

You'd want to consider unique identifying the objects (hash|string, integer) and sharing this reference between clients and the server.

Bear in mind, that if the object reference is process-specific, you won't be able to scale-out the server as the per-process references won't work across processes.

Body:
Does Protocol Buffers support remote object handles? Say to support an API like the following:

service RemoteObjectsDemo {
    rpc AllocateRemoteObject() returns (RemoteObjectHandle);
    rpc UseRemoteObject(RemoteObjectHandle) returns (something);
    rpc FreeRemoteObject(RemoteObjectHandle) returns (Empty);
}

The point is that sometimes all you need is for some object to exist on the server, but there's not need to ever transfer that object across the wire.


问:
Creating vector based on whether dataframe values are divisible by ten
```<code>library(babynames)
</code>```

I am looking to make a vector of all decade marker years AKA years in the babynames package that are divisible by 10.

```<code>range(babynames$year)
</code>```

told me the years in the set are 1880-2017 and I made the following solution

```<code>c(seq(from=1880,to=2017,10))
</code>```

However if the range of babynames did not begin on a number that ended with 10 this example would not work. So now I am looking to find a solution that finds all the decade markers (1890,1900,1910...) between numbers if the first is for ex. 1881

I expect this is possible by checking whether the year between 1881-2017 is divisible by 10 resulting in an integer, and if it is, listing it. How do I do this?

Something like this pseudo code

```<code>for (i in 1881:2017) {
  if (is.integer(i/10)==TRUE)
  c(i)

</code>```

答:
Here is an alternative dplyr approach:

```<code>library(babynames)
library(dplyr)

babynames %>%
  distinct(year) %>%
  filter(year %% 10== 0) %>%
  pull(year)
</code>```
```<code>1880 1890 1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 2010
</code>```

Body:
library(babynames)

I am looking to make a vector of all decade marker years AKA years in the babynames package that are divisible by 10.

range(babynames$year)

told me the years in the set are 1880-2017 and I made the following solution

c(seq(from=1880,to=2017,10))

However if the range of babynames did not begin on a number that ended with 10 this example would not work. So now I am looking to find a solution that finds all the decade markers (1890,1900,1910...) between numbers if the first is for ex. 1881

I expect this is possible by checking whether the year between 1881-2017 is divisible by 10 resulting in an integer, and if it is, listing it. How do I do this?

Something like this pseudo code

for (i in 1881:2017) {
  if (is.integer(i/10)==TRUE)
  c(i)

Body:
Here is an alternative dplyr approach:

library(babynames)
library(dplyr)

babynames %>%
  distinct(year) %>%
  filter(year %% 10== 0) %>%
  pull(year)

1880 1890 1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 2010


问:
Cannot install packages via yarn in electron project (Python syntax error?)
I'm running into an error when trying to install the mitt package in a Quasar / Electron project. I use yarn, but npm runs into the same errors. Perhaps it has to do with me upgrading nodejs recently via the installer on their website instead of via nvm or a similar tool? I'm quite lost at what to do here. Also tried removing node_modules and reinstalling, but same results.

Current node version is 14.15.4.

It looks like the issue asked here, where the solution was downgrading Python to a 2.x version. But Python 2.x is now not supported anymore...

The error messages:

```<code>gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                       ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:308:12)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
gyp ERR! System Windows_NT 10.0.19041
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-gyp\\bin\\node-gyp.js" "configure" "--fallback-to-build" "--module=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64\\node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64" "--napi_version=7" "--node_abi_napi=napi" "--napi_build_version=6" "--node_napi_label=napi-v6"
gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
gyp ERR! node -v v14.15.4
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe D:\Git\libra\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --module=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64 --napi_version=7 --node_abi_napi=napi --napi_build_version=6 --node_napi_label=napi-v6' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (D:\Git\libra\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
node-pre-gyp ERR! System Windows_NT 10.0.19041
node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
node-pre-gyp ERR! node -v v14.15.4
node-pre-gyp ERR! node-pre-gyp -v v0.11.0
</code>```

If helpful, here the full log from running yarn install

```<code>yarn install v1.22.5
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
info fsevents@2.1.3: The platform "win32" is incompatible with this module.
info "fsevents@2.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
info fsevents@1.2.13: The platform "win32" is incompatible with this module.
info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
[4/5] Linking dependencies...
warning "electron-toolkit > bootstrap@4.5.3" has unmet peer dependency "popper.js@^1.16.1".
warning " > eslint-loader@2.2.1" has incorrect peer dependency "eslint@>=1.6.0 <7.0.0".
warning " > eslint-loader@2.2.1" has unmet peer dependency "webpack@>=2.0.0 <5.0.0".
[5/5] Building fresh packages...
[5/5] ⠄ electron
[2/5] ⠄ sqlite3
[3/5] ⠄ node-sass
[-/5] ⠄ waiting...
error D:\Git\libra\node_modules\sqlite3: Command failed.
Exit code: 1
Command: node-pre-gyp install --fallback-to-build
Arguments:
Directory: D:\Git\libra\node_modules\sqlite3
Output:
node-pre-gyp info it worked if it ends with ok
node-pre-gyp info using node-pre-gyp@0.11.0
node-pre-gyp info using node@14.15.4 | win32 | x64
node-pre-gyp WARN Using request for node-pre-gyp https download
node-pre-gyp info check checked for "D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64\node_sqlite3.node" (not found)
node-pre-gyp http GET https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
node-pre-gyp http 403 https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
node-pre-gyp WARN Tried to download(403): https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
node-pre-gyp WARN Pre-built binaries not found for sqlite3@5.0.1 and node@14.15.4 (node-v83 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp http 403 status code downloading tarball https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
gyp info it worked if it ends with ok
gyp info using node-gyp@3.8.0
gyp info using node@14.15.4 | win32 | x64
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@3.8.0
gyp info using node@14.15.4 | win32 | x64
gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                       ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:308:12)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
gyp ERR! System Windows_NT 10.0.19041
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-gyp\\bin\\node-gyp.js" "configure" "--fallback-to-build" "--module=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64\\node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64" "--napi_version=7" "--node_abi_napi=napi" "--napi_build_version=6" "--node_napi_label=napi-v6"
gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
gyp ERR! node -v v14.15.4
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe D:\Git\libra\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --module=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64 --napi_version=7 --node_abi_napi=napi --napi_build_version=6 --node_napi_label=napi-v6' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (D:\Git\libra\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
node-pre-gyp ERR! System Windows_NT 10.0.19041
node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
node-pre-gyp ERR! node -v v14.15.4
node-pre-gyp ERR! node-pre-gyp -v v0.11.0
</code>```

答: Solved by installing python 2.7 and changing path variables.</p>

Body:
I'm running into an error when trying to install the mitt package in a Quasar / Electron project. I use yarn, but npm runs into the same errors. Perhaps it has to do with me upgrading nodejs recently via the installer on their website instead of via nvm or a similar tool? I'm quite lost at what to do here. Also tried removing node_modules and reinstalling, but same results.

Current node version is 14.15.4.

It looks like the issue asked here, where the solution was downgrading Python to a 2.x version. But Python 2.x is now not supported anymore...

The error messages:

gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                       ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:308:12)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
gyp ERR! System Windows_NT 10.0.19041
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-gyp\\bin\\node-gyp.js" "configure" "--fallback-to-build" "--module=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64\\node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64" "--napi_version=7" "--node_abi_napi=napi" "--napi_build_version=6" "--node_napi_label=napi-v6"
gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
gyp ERR! node -v v14.15.4
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe D:\Git\libra\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --module=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64 --napi_version=7 --node_abi_napi=napi --napi_build_version=6 --node_napi_label=napi-v6' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (D:\Git\libra\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
node-pre-gyp ERR! System Windows_NT 10.0.19041
node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
node-pre-gyp ERR! node -v v14.15.4
node-pre-gyp ERR! node-pre-gyp -v v0.11.0

If helpful, here the full log from running yarn install

yarn install v1.22.5
[1/5] Validating package.json...
[2/5] Resolving packages...
[3/5] Fetching packages...
info fsevents@2.1.3: The platform "win32" is incompatible with this module.
info "fsevents@2.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
info fsevents@1.2.13: The platform "win32" is incompatible with this module.
info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
[4/5] Linking dependencies...
warning "electron-toolkit > bootstrap@4.5.3" has unmet peer dependency "popper.js@^1.16.1".
warning " > eslint-loader@2.2.1" has incorrect peer dependency "eslint@>=1.6.0 <7.0.0".
warning " > eslint-loader@2.2.1" has unmet peer dependency "webpack@>=2.0.0 <5.0.0".
[5/5] Building fresh packages...
[5/5] ⠄ electron
[2/5] ⠄ sqlite3
[3/5] ⠄ node-sass
[-/5] ⠄ waiting...
error D:\Git\libra\node_modules\sqlite3: Command failed.
Exit code: 1
Command: node-pre-gyp install --fallback-to-build
Arguments:
Directory: D:\Git\libra\node_modules\sqlite3
Output:
node-pre-gyp info it worked if it ends with ok
node-pre-gyp info using node-pre-gyp@0.11.0
node-pre-gyp info using node@14.15.4 | win32 | x64
node-pre-gyp WARN Using request for node-pre-gyp https download
node-pre-gyp info check checked for "D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64\node_sqlite3.node" (not found)
node-pre-gyp http GET https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
node-pre-gyp http 403 https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
node-pre-gyp WARN Tried to download(403): https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
node-pre-gyp WARN Pre-built binaries not found for sqlite3@5.0.1 and node@14.15.4 (node-v83 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp http 403 status code downloading tarball https://mapbox-node-binary.s3.amazonaws.com/sqlite3/v5.0.1/napi-v6-win32-x64.tar.gz
gyp info it worked if it ends with ok
gyp info using node-gyp@3.8.0
gyp info using node@14.15.4 | win32 | x64
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@3.8.0
gyp info using node@14.15.4 | win32 | x64
gyp ERR! configure error
gyp ERR! stack Error: Command failed: C:\Python39\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                       ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:308:12)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
gyp ERR! System Windows_NT 10.0.19041
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-gyp\\bin\\node-gyp.js" "configure" "--fallback-to-build" "--module=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64\\node_sqlite3.node" "--module_name=node_sqlite3" "--module_path=D:\\Git\\libra\\node_modules\\sqlite3\\lib\\binding\\napi-v6-win32-x64" "--napi_version=7" "--node_abi_napi=napi" "--napi_build_version=6" "--node_napi_label=napi-v6"
gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
gyp ERR! node -v v14.15.4
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe D:\Git\libra\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --module=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64\node_sqlite3.node --module_name=node_sqlite3 --module_path=D:\Git\libra\node_modules\sqlite3\lib\binding\napi-v6-win32-x64 --napi_version=7 --node_abi_napi=napi --napi_build_version=6 --node_napi_label=napi-v6' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (D:\Git\libra\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
node-pre-gyp ERR! System Windows_NT 10.0.19041
node-pre-gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\Git\\libra\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd D:\Git\libra\node_modules\sqlite3
node-pre-gyp ERR! node -v v14.15.4
node-pre-gyp ERR! node-pre-gyp -v v0.11.0


问:
Why does new Object().getClass() == new Object.getClass() always return true? Shouldn't they have different object memory addresses?
```<code>package com.泛型.泛型擦除;

public class Main {
    public static void main(String[] args) {
        Object o = new Object();
        Object o1 = new Object();
        System.out.println(o.getClass() == o1.getClass());
    }
}
</code>```

答:
.getClass() gives you the object's class, so comparing the class of two Objects of the same class (Object.class in this case) will always return true.

You can compare the memory adresses (or, more plainly, if the two objects point to the same object in memory) using == - so

```<code>System.out.println(new Object() == new Object()); //this will return false, as there's two different objects
Object o1 =  new Object();
Object o2 = o1;
System.out.println(o1==o2); //this will return true, as they're the same object
</code>```

Body:
.getClass() gives you the object's class, so comparing the class of two Objects of the same class (Object.class in this case) will always return true.

You can compare the memory adresses (or, more plainly, if the two objects point to the same object in memory) using == - so

System.out.println(new Object() == new Object()); //this will return false, as there's two different objects
Object o1 =  new Object();
Object o2 = o1;
System.out.println(o1==o2); //this will return true, as they're the same object


问:
Saxon EE (java) in a GraalVM native image
We are trying to use Saxon EE in our Quarkus application compiled down into a native image.

It looks like there is a lot of reflection going on in Saxon EE and we are fighting adding all these classes 1 by 1 into our reflection list.

We found this project https://github.com/murphye/saxon-graalvm-native-from-cpp/blob/main/saxon-lib/src/main/resources/reflection-config.json and taking their reflection list really helped us get closer, but there are still EE classes that we need to add to it.

Is there any reflection list out there for Saxon EE? Has anyone built a native version of Saxon EE that we can utilize?

Thank you,
-Jeff

答:
I’ve built a version using Saxon EE and Spring Native. I used the Native Agent to build the reflection list for me. You run this along with the JAR and ‘exercise’ the code paths by running your test suite through it or manual tests. Once you exit the files are created for you.

I was going to raise a question on the Saxonica support forums asking if there were plans to work with Spring and Qurakus to make this process smoother. Sounds like this might be in the works?


问:
How to make a div to be displayed even after refreshing the web page or reopening the browser
Actually I am making a web page using HTML,CSS and Javascript in which there is only one html page with functions like when a person clicks on a particular button, that the current div will not be displayed but the another div will be displayed. At last there will be a home div which will act like the home page of the website.
I want to make that home page to be displayed once a person fills all the credentials and always only the home page should be displayed even after reloading that web page or reopening the web page.
I have researched everywhere but couldn't find the exact solution of the code.
Thanks

答:
Take a look at https://stackblitz.com/edit/web-platform-uawtkc

Tried to simulate the problem and solve it


问:
How do you get relative mouse position inside a VisualElement with new Unity UI Toolkit?
I'm switching over to the new UI-Toolkit (which is css-based). Using the old "canvas" and component-based ui system, I would first see if the mouse was within a ui element with a script attached to that specific ui gameobject with two functions:

```<code>public void OnPointerEnter(PointerEventData eventData)
{
    mouseInScreen = true;
}
public void OnPointerExit(PointerEventData eventData)
{
    mouseInScreen = false;
}
</code>```

Then I would simply call if(OnPointerEnter.mouseInScreen == true) to find out if the mouse is in.

Unfortunately, the new UI uses one gameobject for the entire ui elements, so I'm not sure how to do this. Also, I would need to know the relative position within a UI VisualElement. (ex. mouse is 80px from left, 130px from top of t his specific element).

This new toolkit is amazing, but very new. So it is very hard to find information on it so far.

Thanks.

Edit:

I found a solution to one of the issues I had (how to determine if mouse is over a specific element.)

I used PointerDownEvent since I also need to know when the user clicks in it, but PointerEnterEvent works great for my original question.

```<code>myUIelement.RegisterCallback<PointerDownEvent>(OnPointerDownEvent, TrickleDown.TrickleDown);
</code>```

Then I do what I need in this method

```<code>private void OnPointerDownEvent(PointerDownEvent evt)
{ ... }
</code>```

All I need to figure out is how to get the position of the "pointer" within that ui Element now. There is a property for OnPointerDownEvent called "localPosition", but I'm not sure how to use it exactly.

答:
Here's my own answer after a little help in the comments and doing some research.

First get the element like so:

```<code>VisualElement rootUI = GetComponent<UIDocument>().rootVisualElement;
myUIelement = rootUI.Q<VisualElement>("ElementNameInUIBuilder");
</code>```

Call this in start:

```<code>myUIelement.RegisterCallback<PointerDownEvent>(OnPointerDownEvent, TrickleDown.TrickleDown);
</code>```

Then create a function:

```<code>private void OnPointerDownEvent(PointerDownEvent evt)
</code>```

{ ... }

And in this function just use "evt.localPosition" to get the local coordinates within the ui element.

Body:
I'm switching over to the new UI-Toolkit (which is css-based). Using the old "canvas" and component-based ui system, I would first see if the mouse was within a ui element with a script attached to that specific ui gameobject with two functions:

public void OnPointerEnter(PointerEventData eventData)
{
    mouseInScreen = true;
}
public void OnPointerExit(PointerEventData eventData)
{
    mouseInScreen = false;
}

Then I would simply call if(OnPointerEnter.mouseInScreen == true) to find out if the mouse is in.

Unfortunately, the new UI uses one gameobject for the entire ui elements, so I'm not sure how to do this. Also, I would need to know the relative position within a UI VisualElement. (ex. mouse is 80px from left, 130px from top of t his specific element).

This new toolkit is amazing, but very new. So it is very hard to find information on it so far.

Thanks.

Edit:

I found a solution to one of the issues I had (how to determine if mouse is over a specific element.)

I used PointerDownEvent since I also need to know when the user clicks in it, but PointerEnterEvent works great for my original question.

myUIelement.RegisterCallback<PointerDownEvent>(OnPointerDownEvent, TrickleDown.TrickleDown);

Then I do what I need in this method

private void OnPointerDownEvent(PointerDownEvent evt)
{ ... }

All I need to figure out is how to get the position of the "pointer" within that ui Element now. There is a property for OnPointerDownEvent called "localPosition", but I'm not sure how to use it exactly.

Body:
Here's my own answer after a little help in the comments and doing some research.

First get the element like so:

VisualElement rootUI = GetComponent<UIDocument>().rootVisualElement;
myUIelement = rootUI.Q<VisualElement>("ElementNameInUIBuilder");

Call this in start:

myUIelement.RegisterCallback<PointerDownEvent>(OnPointerDownEvent, TrickleDown.TrickleDown);

Then create a function:

private void OnPointerDownEvent(PointerDownEvent evt)

{ ... }

And in this function just use "evt.localPosition" to get the local coordinates within the ui element.


问:
getting a django textfeild to run as code
I'm trying to get a project going and I'm using Django to do it. I have as one of my attributes in models start_lines = models.TextField(blank=True, null=True). These lines are to get code started with the exec() function. As one of them, I have

```<code>from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.{str(Functions.objects.get(id=request.POST["function_to_call"]))}({request.POST["inputExtras"]}))
</code>```

I have to run this through function to render what i want:

```<code>def showProgramX(request, pk):
    program = Program.objects.get(id=pk)
    form = ProgramInputForm()
    keys = ""
    vars = []
    for var in program.inputvariables.split(","):
        var_name, var_type = var.split("=")
        keys += f"""
            <tr>
            <th><label for="{var_name}">{var_name}:</label></th>
            <td><input type="text" name="{var_name}" maxlength="1000" class="input" id="id_inputvariables"></td>
            </tr>"""
        vars.append(var_name)
    content = {"program": program, "form": form, "keys": keys}
    if request.method == "POST":
        form1 = ProgramInputForm(request.POST)
        import json

        req = request.POST
        for var in vars:
            line = f"""{var} = {req[f'{var}']}"""
            exec(line, globals())

        exec(program.start_lines, globals())
        content["output"] = output
        content["extra_output"] = extra_output
        content['form'] = form1
    return render(request, "programs/program.html", content)
</code>```

the output if i print program.start_lines should be
in this case {str(Functions.objects.get(id=request.POST["function_to_call"]))} = all
and {request.POST["inputExtras"]} is nothing/empty

```<code>from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.all())
</code>```

where as I actually get

```<code>from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.{str(Functions.objects.get(id=request.POST["function_to_call"]))}({request.POST["inputExtras"]}))
</code>```

Does anyone know what I can do to get around this, I've tried everything I can.

答:
I got it. So now just sharing the knowledge.

I used  templates got inspired by https://realpython.com/python-string-formatting/

```<code>from string import Template
t = Template(program.start_lines)
print(t.substitute(function =str(Functions.objects.get(id=request.POST["function_to_call"])), argskwargs=request.POST["inputExtras"] ))
</code>```

and put the following in the text field

```<code>from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.$function($argskwargs))
</code>```

Body:
I'm trying to get a project going and I'm using Django to do it. I have as one of my attributes in models start_lines = models.TextField(blank=True, null=True). These lines are to get code started with the exec() function. As one of them, I have

from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.{str(Functions.objects.get(id=request.POST["function_to_call"]))}({request.POST["inputExtras"]}))

I have to run this through function to render what i want:

def showProgramX(request, pk):
    program = Program.objects.get(id=pk)
    form = ProgramInputForm()
    keys = ""
    vars = []
    for var in program.inputvariables.split(","):
        var_name, var_type = var.split("=")
        keys += f"""

            {var_name}:
            <input type="text" name="{var_name}" maxlength="1000" class="input" id="id_inputvariables">

"""
        vars.append(var_name)
    content = {"program": program, "form": form, "keys": keys}
    if request.method == "POST":
        form1 = ProgramInputForm(request.POST)
        import json

        req = request.POST
        for var in vars:
            line = f"""{var} = {req[f'{var}']}"""
            exec(line, globals())

        exec(program.start_lines, globals())
        content["output"] = output
        content["extra_output"] = extra_output
        content['form'] = form1
    return render(request, "programs/program.html", content)

the output if i print program.start_lines should be
in this case {str(Functions.objects.get(id=request.POST["function_to_call"]))} = all
and {request.POST["inputExtras"]} is nothing/empty

from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.all())

where as I actually get

from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.{str(Functions.objects.get(id=request.POST["function_to_call"]))}({request.POST["inputExtras"]}))

Does anyone know what I can do to get around this, I've tried everything I can.

Body:
I got it. So now just sharing the knowledge.

I used  templates got inspired by https://realpython.com/python-string-formatting/

from string import Template
t = Template(program.start_lines)
print(t.substitute(function =str(Functions.objects.get(id=request.POST["function_to_call"])), argskwargs=request.POST["inputExtras"] ))

and put the following in the text field

from .code.Lot_sizing_codes import lot_size
ls = lot_size(K, h, r, True)
output, extra_output = (ls.$function($argskwargs))


问:
sh: 1: cross-env: Permission denied on laravel mix
I'm trying to run npm run dev but the following error occur:

```<code>sh: 1: cross-env: Permission denied
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/shanmaseen/.npm/_logs/2019-02-22T16_32_08_191Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/shanmaseen/.npm/_logs/2019-02-22T16_32_08_241Z-debug.log
</code>```

I've been searching the internet for a week, nothing helped at all !

I even tried to remove 'cross-env' from package.json scripts, but then webpack: permission denied happened, indicating that the permission error is not by cross-env it self.

this is the error log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'dev' ]
2 info using npm@6.7.0
3 info using node@v11.10.0
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle @~predev: @
6 info lifecycle @~dev: @
7 verbose lifecycle @~dev: unsafe-perm in lifecycle true
8 verbose lifecycle @~dev: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/media/e/www/mwar/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~dev: CWD: /media/e/www/mwar
10 silly lifecycle @~dev: Args: [ '-c', 'npm run development' ]
11 silly lifecycle @~dev: Returned: code: 126  signal: null
12 info lifecycle @~dev: Failed to exec dev script
13 verbose stack Error: @ dev: `npm run development`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:197:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:197:13)
13 verbose stack     at maybeClose (internal/child_process.js:984:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:265:5)
14 verbose pkgid @
15 verbose cwd /media/e/www/mwar
16 verbose Linux 4.18.0-15-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
18 verbose node v11.10.0
19 verbose npm  v6.7.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ dev: `npm run development`
22 error Exit status 126
23 error Failed at the @ dev script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]
</code>```

I'm using laravel 5.7mix.

node version: v11.10.0
npm version: 6.7.0

any help please?

答:
If file and/or directory permissions were changed to more restrictive ones, a permission error like the following can happen on Ubuntu Linux:

```<code>$ npm run watch

> watch
> mix watch

sh: 1: mix: Permission denied
</code>```

to resolve that on Ubuntu Linux, this worked for me:

```<code>chmod -R u+x node_modules
</code>```

It gives+ you as useru executionx permission recursively -R to the node_modules directory and everything inside it.

Be careful, think about security and do not use the a, o nor the g flag instead of the u flag, which would give all, others or group execution rights. The g flag might be ok, if you trust all the users in the group.

As ruuter states in comments, it would be even better for security, if you find the exact file(s) that need execution permission and grant execution permission only for these files.

Body:
I'm trying to run npm run dev but the following error occur:

sh: 1: cross-env: Permission denied
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/shanmaseen/.npm/_logs/2019-02-22T16_32_08_191Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/shanmaseen/.npm/_logs/2019-02-22T16_32_08_241Z-debug.log

I've been searching the internet for a week, nothing helped at all !

I even tried to remove 'cross-env' from package.json scripts, but then webpack: permission denied happened, indicating that the permission error is not by cross-env it self.

this is the error log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'dev' ]
2 info using npm@6.7.0
3 info using node@v11.10.0
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle @~predev: @
6 info lifecycle @~dev: @
7 verbose lifecycle @~dev: unsafe-perm in lifecycle true
8 verbose lifecycle @~dev: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/media/e/www/mwar/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
9 verbose lifecycle @~dev: CWD: /media/e/www/mwar
10 silly lifecycle @~dev: Args: [ '-c', 'npm run development' ]
11 silly lifecycle @~dev: Returned: code: 126  signal: null
12 info lifecycle @~dev: Failed to exec dev script
13 verbose stack Error: @ dev: `npm run development`
13 verbose stack Exit status 126
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:197:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:197:13)
13 verbose stack     at maybeClose (internal/child_process.js:984:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:265:5)
14 verbose pkgid @
15 verbose cwd /media/e/www/mwar
16 verbose Linux 4.18.0-15-generic
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
18 verbose node v11.10.0
19 verbose npm  v6.7.0
20 error code ELIFECYCLE
21 error errno 126
22 error @ dev: `npm run development`
22 error Exit status 126
23 error Failed at the @ dev script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 126, true ]

I'm using laravel 5.7mix.

node version: v11.10.0
npm version: 6.7.0

any help please?

Body:
If file and/or directory permissions were changed to more restrictive ones, a permission error like the following can happen on Ubuntu Linux:

$ npm run watch

> watch
> mix watch

sh: 1: mix: Permission denied

to resolve that on Ubuntu Linux, this worked for me:

chmod -R u+x node_modules

It gives+ you as useru executionx permission recursively -R to the node_modules directory and everything inside it.

Be careful, think about security and do not use the a, o nor the g flag instead of the u flag, which would give all, others or group execution rights. The g flag might be ok, if you trust all the users in the group.

As ruuter states in comments, it would be even better for security, if you find the exact file(s) that need execution permission and grant execution permission only for these files.


问:
Can't access variable in function
Javascript noob here. I'm having a problem with the variable "meal", which can't be accessed for some reason. I returned it from the getMealById() function so i thought that would make it accessible in another function but somehow i can't access that variable.(last 2 lines of code). If anyone sees what i'm doing wrong, i would gladly appreciate your help. I've been awake till 6am yesterday trying to find it without success. I came here because i don't know where else to ask now. Thanks in advance!

```<code>const meals = document.getElementById("meals");

getRandomMeal();
fetchFavMeals();

async function getRandomMeal() {
  const resp = await fetch(
    "https://www.themealdb.com/api/json/v1/1/random.php"
  );

  const respData = await resp.json();
  const randomMeal = respData.meals[0];

  addMeal(randomMeal, true);
}

async function getMealById(id) {
  const resp = await fetch(
    "https://www.themealdb.com/api/json/v1/1/lookup.php?i=" + id
  );

  const respData = await resp.json();

  const meal = respData.meals[0];

  return meal;
}

async function getMealBySearch(term) {
  const meals = await fetch(
    "https://www.themealdb.com/api/json/v1/1/search.php?s=" + term
  );
}

function addMeal(mealData, random = false) {
  console.log(mealData);
  const meal = document.createElement("div");
  meal.classList.add("meal");

  meal.innerHTML = `
  <div class="meal-header">
    ${random ? `<span class="random">Random Recipe</span>` : ""}
    <img
    src="${mealData.strMealThumb}"
    alt="${mealData.strMeal}"
  />
  </div>
  <div class="meal-body">
    <h4>${mealData.strMeal}</h4>
    <button class="fav-btn">
      <i class="fas fa-heart"></i>
    </button>
  </div>`;

  const btn = meal.querySelector(".meal-body .fav-btn");

  btn.addEventListener("click", () => {
    if (btn.classList.contains("active")) {
      removeMealLS(mealData.idMeal);
      btn.classList.remove("active");
    } else {
      addMealLS(mealData.idMeal);
      btn.classList.add("active");
    }
  });

  meals.appendChild(meal);
}

function addMealLS(mealId) {
  const mealIds = getMealsLS();
  localStorage.setItem("mealIds", JSON.stringify([...mealIds, mealId]));
}

function removeMealLS(mealId) {
  const mealIds = getMealsLS();

  localStorage.setItem(
    "mealIds",
    JSON.stringify(mealIds.filter((id) => id !== mealId))
  );
}

function getMealsLS() {
  const mealIds = JSON.parse(localStorage.getItem("mealIds"));
  return mealIds === null ? [] : mealIds;
}

async function fetchFavMeals() {
  const mealIds = getMealsLS();

  const meals = [];

  for (let i = 0; i < mealIds.length; i++) {
    const mealId = mealIds[i];

    meal = await getMealById(mealId);

    meals.push(meal);
  }
}
</code>```

答: You are missing the variable declaration in the fetchFavMeals function for variable meal. Just use let or const for it. After that you will be able to access.

Title: Can't access variable in function

Body:
Javascript noob here. I'm having a problem with the variable "meal", which can't be accessed for some reason. I returned it from the getMealById() function so i thought that would make it accessible in another function but somehow i can't access that variable.(last 2 lines of code). If anyone sees what i'm doing wrong, i would gladly appreciate your help. I've been awake till 6am yesterday trying to find it without success. I came here because i don't know where else to ask now. Thanks in advance!

const meals = document.getElementById("meals");

getRandomMeal();
fetchFavMeals();

async function getRandomMeal() {
  const resp = await fetch(
    "https://www.themealdb.com/api/json/v1/1/random.php"
  );

  const respData = await resp.json();
  const randomMeal = respData.meals[0];

  addMeal(randomMeal, true);
}

async function getMealById(id) {
  const resp = await fetch(
    "https://www.themealdb.com/api/json/v1/1/lookup.php?i=" + id
  );

  const respData = await resp.json();

  const meal = respData.meals[0];

  return meal;
}

async function getMealBySearch(term) {
  const meals = await fetch(
    "https://www.themealdb.com/api/json/v1/1/search.php?s=" + term
  );
}

function addMeal(mealData, random = false) {
  console.log(mealData);
  const meal = document.createElement("div");
  meal.classList.add("meal");

  meal.innerHTML = `

    ${random ? `<span class="random">Random Recipe</span>` : ""}

${mealData.strMeal}

    <button class="fav-btn">

    </button>

`;

  const btn = meal.querySelector(".meal-body .fav-btn");

  btn.addEventListener("click", () => {
    if (btn.classList.contains("active")) {
      removeMealLS(mealData.idMeal);
      btn.classList.remove("active");
    } else {
      addMealLS(mealData.idMeal);
      btn.classList.add("active");
    }
  });

  meals.appendChild(meal);
}

function addMealLS(mealId) {
  const mealIds = getMealsLS();
  localStorage.setItem("mealIds", JSON.stringify([...mealIds, mealId]));
}

function removeMealLS(mealId) {
  const mealIds = getMealsLS();

  localStorage.setItem(
    "mealIds",
    JSON.stringify(mealIds.filter((id) => id !== mealId))
  );
}

function getMealsLS() {
  const mealIds = JSON.parse(localStorage.getItem("mealIds"));
  return mealIds === null ? [] : mealIds;
}

async function fetchFavMeals() {
  const mealIds = getMealsLS();

  const meals = [];

  for (let i = 0; i < mealIds.length; i++) {
    const mealId = mealIds[i];

    meal = await getMealById(mealId);

    meals.push(meal);
  }
}


问:
Woocommerce which hook to use for order status changes
In my custom plugin I need to catch every time an order status changes from wc_on_hold to wc_completed so I tried to write down:

```<code>function so_status_completed( $order_id, $old_status, $new_status ) {

    // if user is active , then get order amount and do all other personal calculations

    global $wpdb;
    $order = wc_get_order( $order_id );
    //$payment_method = $order->get_payment_method(); //returns payment method bacs,cheque,cod etc
    $user_id = $order->get_user_id();
    $total = $order->get_total();
    $order_data = $order->get_data();
    //$order_total = $order->get_formatted_order_total();
    $order_total = $order->get_total();

    echo '<script>console.log("Debug Objects: Check order_total ' . $order_total. '");</script>';

}
add_action('woocommerce_order_payment_status_changed','so_status_completed',10,1);
</code>```

But when I tried to change an order test from suspended to completed, I couldn't get on Chrome's Console that echo giving me the order price.....maybe using add_action isn't the right way to put a listener to that event?

Plus, since I am just here, I am using $order-get_total() which I searched on the net about his functionality but no deep docs found so I want to ask you if that method is the right one to retrieve order amount without fee applied?

Thanks! Cheers!!!

答:
"I need to catch every time an order status changes from wc_on_hold to wc_completed"

You would need to change your hook to woocommerce_order_status_changed.

"I couldn't get on Chrome's Console that echo giving me the order price"

You can't use javascript and console.log in this hook. You would need to either use the die function or the error_log function to log it to your debug.log file.

1- Using die function

add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

    $order = wc_get_order($order_id);

    //$order_total = $order->get_formatted_order_total();
    $order_total = $order->get_total();

    die($order_total);
}
```
<hr />
<h3>2- Using <code>error_log</code> function</h3>
<pre class="lang-php prettyprint-override"><code>add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

    $order = wc_get_order($order_id);

    //$order_total = $order->get_formatted_order_total();
    $order_total = $order->get_total();

    error_log(print_r('order total: ' . $order_total, true));
}
</code>```

Note:

In order for this to work, you would need to activate "debugging" mode in your wp-config.php file. So, navigate to your wp-config.php file and add the following lines to it!

(NOT RECOMMENDED IN THE PRODUCTION)

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
```
<hr />
<h3>3- Creating a simple logger using <code>file_put_contents</code> function!</h3>
<pre class="lang-php prettyprint-override"><code>add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

  $order = wc_get_order($order_id);

  //$order_total = $order->get_formatted_order_total();
  $order_total = $order->get_total();

  // Simple logger
  file_put_contents(dirname(__FILE__) . '/my_logger.txt', $order_total);
}
</code>```

If "my_logger.txt" does not exist, it'll be created. If it already exists, then it'll be overwritten!

You could use "append" mode with your logger, if you need to! So your logger file won't get overwritten.

add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

  $order = wc_get_order($order_id);

  //$order_total = $order->get_formatted_order_total();
  $order_total = $order->get_total();

  // Logger with "append" mode
  file_put_contents(dirname(__FILE__) . '/my_logger.txt', $order_total, FILE_APPEND);
}
```

Second question

"since I am just here, I want to ask you if $order-get_total() is the right one to retrieve order amount without fee applied?"

You might want to take a look at the $order->get_subtotal() for the totals before shipping, coupons and taxes:

Please see these related answers:

https://stackoverflow.com/a/47782647/15040627

https://stackoverflow.com/a/61102779/15040627

https://stackoverflow.com/a/32634480/15040627

https://stackoverflow.com/a/44708344/15040627

Body:
In my custom plugin I need to catch every time an order status changes from wc_on_hold to wc_completed so I tried to write down:

function so_status_completed( $order_id, $old_status, $new_status ) {

    // if user is active , then get order amount and do all other personal calculations

    global $wpdb;
    $order = wc_get_order( $order_id );
    //$payment_method = $order->get_payment_method(); //returns payment method bacs,cheque,cod etc
    $user_id = $order->get_user_id();
    $total = $order->get_total();
    $order_data = $order->get_data();
    //$order_total = $order->get_formatted_order_total();
    $order_total = $order->get_total();

    echo '';

}
add_action('woocommerce_order_payment_status_changed','so_status_completed',10,1);

But when I tried to change an order test from suspended to completed, I couldn't get on Chrome's Console that echo giving me the order price.....maybe using add_action isn't the right way to put a listener to that event?

Plus, since I am just here, I am using $order-get_total() which I searched on the net about his functionality but no deep docs found so I want to ask you if that method is the right one to retrieve order amount without fee applied?

Thanks! Cheers!!!

Body:
"I need to catch every time an order status changes from wc_on_hold to wc_completed"

You would need to change your hook to woocommerce_order_status_changed.

"I couldn't get on Chrome's Console that echo giving me the order price"

You can't use javascript and console.log in this hook. You would need to either use the die function or the error_log function to log it to your debug.log file.

1- Using die function

add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

    $order = wc_get_order($order_id);

    //$order_total = $order->get_formatted_order_total();
    $order_total = $order->get_total();

    die($order_total);
}

2- Using error_log function

add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

    $order = wc_get_order($order_id);

    //$order_total = $order->get_formatted_order_total();
    $order_total = $order->get_total();

    error_log(print_r('order total: ' . $order_total, true));
}

Note:

In order for this to work, you would need to activate "debugging" mode in your wp-config.php file. So, navigate to your wp-config.php file and add the following lines to it!

(NOT RECOMMENDED IN THE PRODUCTION)

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

3- Creating a simple logger using file_put_contents function!

add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

  $order = wc_get_order($order_id);

  //$order_total = $order->get_formatted_order_total();
  $order_total = $order->get_total();

  // Simple logger
  file_put_contents(dirname(__FILE__) . '/my_logger.txt', $order_total);
}

If "my_logger.txt" does not exist, it'll be created. If it already exists, then it'll be overwritten!

You could use "append" mode with your logger, if you need to! So your logger file won't get overwritten.

add_action('woocommerce_order_status_changed', 'so_status_completed', 10, 3);

function so_status_completed($order_id, $old_status, $new_status)
{

  $order = wc_get_order($order_id);

  //$order_total = $order->get_formatted_order_total();
  $order_total = $order->get_total();

  // Logger with "append" mode
  file_put_contents(dirname(__FILE__) . '/my_logger.txt', $order_total, FILE_APPEND);
}

Second question

"since I am just here, I want to ask you if $order-get_total() is the right one to retrieve order amount without fee applied?"

You might want to take a look at the $order->get_subtotal() for the totals before shipping, coupons and taxes:

Please see these related answers:

https://stackoverflow.com/a/47782647/15040627

https://stackoverflow.com/a/61102779/15040627

https://stackoverflow.com/a/32634480/15040627

https://stackoverflow.com/a/44708344/15040627


问:
How to manipulate timing and typescript files created by "script" command?
As an important step of debugging process, looking finely for times and progressions is as must have.

Using script and scriptreplay oftenly, I wonder if there exist tools for manipulating resulting files.

Sample (From How to profile a bash shell script slow startup?):

```<code>script -t script.log 2>script.tim -c 'bash -x -c "
    for ((i=3;i--;));do sleep .1;done

    for ((i=2;i--;)) ;do
        tar -cf /tmp/test.tar -C / bin
        gzip /tmp/test.tar
        rm /tmp/test.tar.gz
    done
"'
</code>```

Then there are two files:

```<code>-rw-r--r-- 1 user  user  472 Sep 25 10:44 script.log
-rw-r--r-- 1 user  user  213 Sep 25 10:44 script.tim
</code>```

And I could replay the script by:

```<code>scriptreplay --timing script.tim --typescript script.log 10
</code>```

with 10 as execution time divisor to make replay 10x quicker, or

```<code>scriptreplay --timing script.tim --typescript script.log .1
</code>```

to make replay 10x slower.

I wonder if there exist tools like:

Well, from there:

```<code>cut -d \  -f1 <script.tim | xargs  | tr \  + | bc
3.616809
</code>```

will output overall execution time or if there is too much lines:

```<code>cut -d \  -f1 <script.tim | xargs  | tr \  + | bc | xargs  | tr \  + | bc
3.616809
</code>```

and

```<code>cut -d \  -f2 <script.tim | xargs  | tr \  + | bc
366
sed '1d;$d' script.log |wc -c
367
</code>```

to check overall script ouptut size. (sed drop 1st and last lines of log, who contain: Script started on Wed Sep 25 14:40:20 2019 and Script done on Wed Sep 25 14:40:23 2019.)

Then, computing log size (pointer) at some time:

```<code>perl -e 'my ($l,$t,$p)=(0,0,0); # line totTime pos
    open FH,"<".$ARGV[0] || die;
    while (<FH>) {
        my ($d,$n)=split" "; # duration numBytes
        $l++;
        $t+=$d;
        $p+=$n;
        $t>=${ARGV[1]} && do {
            print $l." ".$p."\n";
            exit 0;
        };
    };' script.tim  1.2
12 216
</code>```

Line 12 in timingfile (head -n 12) and byte position 216 in typescript file (head -c 216).

Or if I'm searching for time elapsed upto some string:

```<code>grep -ob 'tar.*test' script.log
217:tar -cf /tmp/test
320:tar -cf /tmp/test

perl -e 'my ($l,$t,$p)=(0,0,0);open FH,"<".$ARGV[0] || die;while (<FH>) {
    my ($d,$n)=split" ";$l++;$t+=$d;$p+=$n;$p>=${ARGV[1]} && do {
      print $l." ".$p."\n";exit 0;};};' script.tim  217
17 228

head -n 17 script.tim | cut -d \  -f1 | xargs | tr \  + | bc
1.091276
</code>```

My request:

Searching for something lighter...

This could be some pieces of small script, using python in order to modernize my pieces of perl.

Even dynamic! I could imagine a tool using NCurses, with a progress bar, some display and some keyboard control, like a kind of video viewer: Start, Stop, Next step, ...

答:
Here is a 1st try, bash based

This use (require) xterm and run replay script output in a new terminal with same size than script was runned in. Interaction are really minimalist.

Here are two options:

-t Do timelaps by using builtin read so able to be accelerated by hitting Return.

-w To submit a word or string to search for. Progression will be stopped until you press Return.

```<code>#!/bin/bash
export LANG=C LANGUAGE=C
die() { echo >&2 "$0 ERR: $@";exit 1;}
doTime=false
while getopts "tw:" opt;do case $opt in
                       t ) doTime=true;;
                       w ) searchFor=${OPTARG};;
                   esac;done
shift $((OPTIND-1))
</code>```

```<code>exec {log}<"$1" || die "Can't open logfile '$1'."
exec {tim}<"$2" || die "Can't open timing file '$2'-"
IFS='' read -ru $log line || die "error reading logfile."
sTerm=${line#*TERM=\"} sTerm=${sTerm%%\"*}
sCols=${line#*COLUMNS=\"} sCols=${sCols%%\"*}
sLnes=${line#*LINES=\"} sLnes=${sLnes%%\"*}
[ "$sTerm" ] || die "No TERM var found."
((sCols * sLnes)) || die "No valid size"

exec {term}<> >(:)
xterm -fs 11 -geom ${sCols}x$sLnes -T ScripReplay -S00/$term &
XTPid=$!
read -u $term -t 1 XTWinId
</code>```

```<code>declare -i TTime=0   TChar=0
while read -u $tim time chars;do
    IFS='' read -d '' -rn $chars -u $log str
    printf >&$term '%s' "$str"
    TTime+=10#${time/.}    TChar+=chars
    ttm=00000$TTime
    printf "\rCrt %12.6f, %3d chars - Tot:  %12.6f %11d\n" $time $chars \
           ${ttm::-6}.${ttm: -6} $TChar
    [ "$searchFor" ] &&
        case $str in *$searchFor* ) read -p "Found: '$searchFor'. " _;;esac
    $doTime && read -t $time _
done

exec {tim}<&-
exec {log}<&-
read -pDone.\  _
exec {term}>&-
kill $XTPid
</code>```

Same in python would be welcome!

More featured version on my website:

Here: scriptReplay.sh.txt, scriptReplay.sh.

```<code>Script Replay based debugging tool

Command line optional arguments:
  -h         Show this.
  -t         Reproduce delays between outputs ('$doTime', default false)
  -d DIVISOR Integer divisor of delay [-t] ('$divisor', default 10)
  -w STRING  Stop output when STRING found, wait for user interaction
  -n         Don't wait when STRING found

Interactive interface: Once run, ${0##*/} will open another xterm
window to show console dialog as recorded by script.
While running, interaction in first console could be:
  [t]       Toggle reproducing time delays between outputs
  [d]       Enter a new INTEGER for divisor
  [s]       Enter a new STRING to search for
  [q]       Quit.
</code>```

Yet another bash script

Here is a small and fast solution (using bc):

#!/bin/bash

coproc exec bc
echo >&${COPROC[1]} t=0.0
{
    declare -i Tlen=0
    read -u $lg hl
    echo HEAD $hl
    while read -u $tm tim chrs ;do
        echo "t+=$tim;t" >&${COPROC[1]}
        read -u ${COPROC[0]} Ttim
        Tlen+=$chrs
        LANG=C IFS='' read -d '' -u $lg -rn $chrs str
        printf '%10.6f %-4d|%12.6f %12d: %s\n' $tim $chrs $Ttim $Tlen "${str@Q}"
    done
    while read -u $lg str ;do
        echo "TAIL: ${str@Q}"
    done
} {lg}<"$1" {tm}<"$2"
```
<p>Run on <code>script.log</code> and <code>script.tim</code> produced by 1st command in this post will render on my raspberry-pi:</p>
<pre class="lang-none prettyprint-override"><code>$ ./quickReplay.sh script.{log,tim}
HEAD Script started on 2022-04-07 14:37:19+02:00 [TERM="xterm" TTY="/dev/pts/0" COLUMNS="80" LINES="24"]
  0.083946 11  |    0.083946           11: '+ (( i=3 ))'
  0.001231 2   |    0.085177           13: $'\r\n'
  0.001951 11  |    0.087128           24: '+ (( i-- ))'
  0.001023 2   |    0.088151           26: $'\r\n'
  0.001947 10  |    0.090098           36: '+ sleep .1'
  0.001412 2   |    0.091510           38: $'\r\n'
  0.123944 9   |    0.215454           47: '+ (( 1 ))'
  0.005763 2   |    0.221217           49: $'\r\n'
  0.001559 11  |    0.222776           60: '+ (( i-- ))'
  0.001027 2   |    0.223803           62: $'\r\n'
  0.001908 10  |    0.225711           72: '+ sleep .1'
  0.001256 2   |    0.226967           74: $'\r\n'
  0.126024 9   |    0.352991           83: '+ (( 1 ))'
  0.001316 2   |    0.354307           85: $'\r\n'
  0.001804 11  |    0.356111           96: '+ (( i-- ))'
  0.001076 2   |    0.357187           98: $'\r\n'
  0.002086 10  |    0.359273          108: '+ sleep .1'
  0.002059 2   |    0.361332          110: $'\r\n'
  0.125725 9   |    0.487057          119: '+ (( 1 ))'
  0.001147 2   |    0.488204          121: $'\r\n'
  0.001768 11  |    0.489972          132: '+ (( i-- ))'
  0.001346 2   |    0.491318          134: $'\r\n'
  0.002247 11  |    0.493565          145: '+ (( i=2 ))'
  0.007743 2   |    0.501308          147: $'\r\n'
  0.001628 11  |    0.502936          158: '+ (( i-- ))'
  0.000259 2   |    0.503195          160: $'\r\n'
  0.000810 32  |    0.504005          192: '+ tar -cf /tmp/test.tar -C / bin'
  0.001128 2   |    0.505133          194: $'\r\n'
  1.336998 20  |    1.842131          214: '+ gzip /tmp/test.tar'
  0.001093 2   |    1.843224          216: $'\r\n'
 34.593442 23  |   36.436666          239: $'+ rm /tmp/test.tar.gz\r\n'
  0.041637 9   |   36.478303          248: '+ (( 1 ))'
  0.001435 2   |   36.479738          250: $'\r\n'
  0.001617 11  |   36.481355          261: '+ (( i-- ))'
  0.010704 2   |   36.492059          263: $'\r\n'
  0.001931 32  |   36.493990          295: '+ tar -cf /tmp/test.tar -C / bin'
  0.001085 2   |   36.495075          297: $'\r\n'
  0.737705 20  |   37.232780          317: '+ gzip /tmp/test.tar'
  0.001179 2   |   37.233959          319: $'\r\n'
 35.705253 21  |   72.939212          340: '+ rm /tmp/test.tar.gz'
  0.001160 2   |   72.940372          342: $'\r\n'
  0.053247 9   |   72.993619          351: '+ (( 1 ))'
  0.001170 2   |   72.994789          353: $'\r\n'
  0.002150 11  |   72.996939          364: '+ (( i-- ))'
  0.001353 2   |   72.998292          366: $'\r\n'
TAIL: ''
TAIL: 'Script done on 2022-04-07 14:38:32+02:00 [COMMAND_EXIT_CODE="0"]'
</code>```

Body:
As an important step of debugging process, looking finely for times and progressions is as must have.

Using script and scriptreplay oftenly, I wonder if there exist tools for manipulating resulting files.

Sample (From How to profile a bash shell script slow startup?):

script -t script.log 2>script.tim -c 'bash -x -c "
    for ((i=3;i--;));do sleep .1;done

    for ((i=2;i--;)) ;do
        tar -cf /tmp/test.tar -C / bin
        gzip /tmp/test.tar
        rm /tmp/test.tar.gz
    done
"'

Then there are two files:

-rw-r--r-- 1 user  user  472 Sep 25 10:44 script.log
-rw-r--r-- 1 user  user  213 Sep 25 10:44 script.tim

And I could replay the script by:

scriptreplay --timing script.tim --typescript script.log 10

with 10 as execution time divisor to make replay 10x quicker, or

scriptreplay --timing script.tim --typescript script.log .1

to make replay 10x slower.

I wonder if there exist tools like:

Well, from there:

cut -d \  -f1

Body:
Here is a 1st try, bash based

This use (require) xterm and run replay script output in a new terminal with same size than script was runned in. Interaction are really minimalist.

Here are two options:

-t Do timelaps by using builtin read so able to be accelerated by hitting Return.

-w To submit a word or string to search for. Progression will be stopped until you press Return.

#!/bin/bash
export LANG=C LANGUAGE=C
die() { echo >&2 "$0 ERR: $@";exit 1;}
doTime=false
while getopts "tw:" opt;do case $opt in
                       t ) doTime=true;;
                       w ) searchFor=${OPTARG};;
                   esac;done
shift $((OPTIND-1))

exec {log}<"$1" || die "Can't open logfile '$1'."
exec {tim}<"$2" || die "Can't open timing file '$2'-"
IFS='' read -ru $log line || die "error reading logfile."
sTerm=${line#*TERM=\"} sTerm=${sTerm%%\"*}
sCols=${line#*COLUMNS=\"} sCols=${sCols%%\"*}
sLnes=${line#*LINES=\"} sLnes=${sLnes%%\"*}
[ "$sTerm" ] || die "No TERM var found."
((sCols * sLnes)) || die "No valid size"

exec {term}<> >(:)
xterm -fs 11 -geom ${sCols}x$sLnes -T ScripReplay -S00/$term &
XTPid=$!
read -u $term -t 1 XTWinId

declare -i TTime=0   TChar=0
while read -u $tim time chars;do
    IFS='' read -d '' -rn $chars -u $log str
    printf >&$term '%s' "$str"
    TTime+=10#${time/.}    TChar+=chars
    ttm=00000$TTime
    printf "\rCrt %12.6f, %3d chars - Tot:  %12.6f %11d\n" $time $chars \
           ${ttm::-6}.${ttm: -6} $TChar
    [ "$searchFor" ] &&
        case $str in *$searchFor* ) read -p "Found: '$searchFor'. " _;;esac
    $doTime && read -t $time _
done

exec {tim}<&-
exec {log}<&-
read -pDone.\  _
exec {term}>&-
kill $XTPid

Same in python would be welcome!

More featured version on my website:

Here: scriptReplay.sh.txt, scriptReplay.sh.

Script Replay based debugging tool

Command line optional arguments:
  -h         Show this.
  -t         Reproduce delays between outputs ('$doTime', default false)
  -d DIVISOR Integer divisor of delay [-t] ('$divisor', default 10)
  -w STRING  Stop output when STRING found, wait for user interaction
  -n         Don't wait when STRING found

Interactive interface: Once run, ${0##*/} will open another xterm
window to show console dialog as recorded by script.
While running, interaction in first console could be:
  [t]       Toggle reproducing time delays between outputs
  [d]       Enter a new INTEGER for divisor
  [s]       Enter a new STRING to search for
  [q]       Quit.

Yet another bash script

Here is a small and fast solution (using bc):

#!/bin/bash

coproc exec bc
echo >&${COPROC[1]} t=0.0
{
    declare -i Tlen=0
    read -u $lg hl
    echo HEAD $hl
    while read -u $tm tim chrs ;do
        echo "t+=$tim;t" >&${COPROC[1]}
        read -u ${COPROC[0]} Ttim
        Tlen+=$chrs
        LANG=C IFS='' read -d '' -u $lg -rn $chrs str
        printf '%10.6f %-4d|%12.6f %12d: %s\n' $tim $chrs $Ttim $Tlen "${str@Q}"
    done
    while read -u $lg str ;do
        echo "TAIL: ${str@Q}"
    done
} {lg}<"$1" {tm}<"$2"

Run on script.log and script.tim produced by 1st command in this post will render on my raspberry-pi:

$ ./quickReplay.sh script.{log,tim}
HEAD Script started on 2022-04-07 14:37:19+02:00 [TERM="xterm" TTY="/dev/pts/0" COLUMNS="80" LINES="24"]
  0.083946 11  |    0.083946           11: '+ (( i=3 ))'
  0.001231 2   |    0.085177           13: $'\r\n'
  0.001951 11  |    0.087128           24: '+ (( i-- ))'
  0.001023 2   |    0.088151           26: $'\r\n'
  0.001947 10  |    0.090098           36: '+ sleep .1'
  0.001412 2   |    0.091510           38: $'\r\n'
  0.123944 9   |    0.215454           47: '+ (( 1 ))'
  0.005763 2   |    0.221217           49: $'\r\n'
  0.001559 11  |    0.222776           60: '+ (( i-- ))'
  0.001027 2   |    0.223803           62: $'\r\n'
  0.001908 10  |    0.225711           72: '+ sleep .1'
  0.001256 2   |    0.226967           74: $'\r\n'
  0.126024 9   |    0.352991           83: '+ (( 1 ))'
  0.001316 2   |    0.354307           85: $'\r\n'
  0.001804 11  |    0.356111           96: '+ (( i-- ))'
  0.001076 2   |    0.357187           98: $'\r\n'
  0.002086 10  |    0.359273          108: '+ sleep .1'
  0.002059 2   |    0.361332          110: $'\r\n'
  0.125725 9   |    0.487057          119: '+ (( 1 ))'
  0.001147 2   |    0.488204          121: $'\r\n'
  0.001768 11  |    0.489972          132: '+ (( i-- ))'
  0.001346 2   |    0.491318          134: $'\r\n'
  0.002247 11  |    0.493565          145: '+ (( i=2 ))'
  0.007743 2   |    0.501308          147: $'\r\n'
  0.001628 11  |    0.502936          158: '+ (( i-- ))'
  0.000259 2   |    0.503195          160: $'\r\n'
  0.000810 32  |    0.504005          192: '+ tar -cf /tmp/test.tar -C / bin'
  0.001128 2   |    0.505133          194: $'\r\n'
  1.336998 20  |    1.842131          214: '+ gzip /tmp/test.tar'
  0.001093 2   |    1.843224          216: $'\r\n'
 34.593442 23  |   36.436666          239: $'+ rm /tmp/test.tar.gz\r\n'
  0.041637 9   |   36.478303          248: '+ (( 1 ))'
  0.001435 2   |   36.479738          250: $'\r\n'
  0.001617 11  |   36.481355          261: '+ (( i-- ))'
  0.010704 2   |   36.492059          263: $'\r\n'
  0.001931 32  |   36.493990          295: '+ tar -cf /tmp/test.tar -C / bin'
  0.001085 2   |   36.495075          297: $'\r\n'
  0.737705 20  |   37.232780          317: '+ gzip /tmp/test.tar'
  0.001179 2   |   37.233959          319: $'\r\n'
 35.705253 21  |   72.939212          340: '+ rm /tmp/test.tar.gz'
  0.001160 2   |   72.940372          342: $'\r\n'
  0.053247 9   |   72.993619          351: '+ (( 1 ))'
  0.001170 2   |   72.994789          353: $'\r\n'
  0.002150 11  |   72.996939          364: '+ (( i-- ))'
  0.001353 2   |   72.998292          366: $'\r\n'
TAIL: ''
TAIL: 'Script done on 2022-04-07 14:38:32+02:00 [COMMAND_EXIT_CODE="0"]'


问:
Handle .net exceptions at application level
I was reading a couple of articles a while back which I think described a behaviour where you can, in a .net application (specifically VB.net), allow an exception to occur, and then handle it in some kind of application-level exception handler, as opposed to within a Try/Catch block.
My google-fu is weak at the moment, so I'm not having much luck guessing what this feature is called in order to find information about it.

If this rings a bell for any of you, can you point me in the right direction on what exactly the feature is called so that I can search for it?

Sample code is always welcome, of course, but this is mostly just a case of me forgetting the name of the feature and being unable to search for it.

答: This link http://msdn.microsoft.com/en-us/library/3a02k5s0(VS.80).aspx  will show you how to add the handler.  I agree that it is not a good idea to handle exceptions this way.  IMHO it is the handler of last resort.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dbasnett


问:
Create a masterpage that fits any screen resolution
I have created a masterpage and I want the ASP.NET pages attached to it to fit any screen resolution. Its a html tables based design.

I read that if you keep tables width and height to 100% then it should fit to any resolution. I have done the same thing, it adjusts its width to any screen resolution but not height. We see a blank space at the bottom for heigher screen resolutions and creates a scroll bar for lower screen resolutions.

Anyone has any idea how to fix this issue?

答:
Intstead of table based page you should go for DIV based pages.. Its generally easy to create and handle. As far as height is concerned, u shouldn't be worried about it as height may increase with the content.. Personally, whenever I want to go with full width, I break my HTML in three parts..

Header

Main Content

Footer

I keep eader and footer div to full body width while Main Content is normally 900px wide.. I gives nice clean effect of full width page :)

hope it helps :)


问:
replace list of sentence to the text
I am trying to replace the text if it contains the sentences from a list1.

I tried the following code, but it's not working:

```<code>text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
  if i in text:
    text.replace(i,"")

#wrong output:
'what a lovely car it is , i love it by the way it looks and the color is so good. i am feeling very happy after seeing it'
</code>```

Expected output:

```<code>'what a , i love it by the way it looks and the . i am feeling very seeing it'
</code>```

答:
Python strings are immutable; the str.replace() method doesn't alter the existing string, but rather, it returns a new string based on the existing string.

So simply replace text.replace(i,"") with text = text.replace(i,""). Observe:

```<code>text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

for i in list1:
  if i in text:
    text = text.replace(i, "")

print(text)
</code>```

Output:

```<code>what a  , i love it by the way it looks and the  . i am feeling very  seeing it
</code>```

Title: replace list of sentence to the text

Body:
I am trying to replace the text if it contains the sentences from a list1.

I tried the following code, but it's not working:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

#code i tried
for i in list1:
  if i in text:
    text.replace(i,"")

#wrong output:
'what a lovely car it is , i love it by the way it looks and the color is so good. i am feeling very happy after seeing it'

Expected output:

'what a , i love it by the way it looks and the . i am feeling very seeing it'

Body:
Python strings are immutable; the str.replace() method doesn't alter the existing string, but rather, it returns a new string based on the existing string.

So simply replace text.replace(i,"") with text = text.replace(i,""). Observe:

text = "what a lovely car it is , i love it by the way it looks and the color is so good . i am feeling very happy after ) seeing it"
list1 = ['lovely car it is', 'color is so good','happy after )']

for i in list1:
  if i in text:
    text = text.replace(i, "")

print(text)

Output:

what a  , i love it by the way it looks and the  . i am feeling very  seeing it


问:
Store select query's output in one array in postgres
My code is:

```<code>SELECT column_name
FROM information.SCHEMA.columns
WHERE table_name = 'aean'
</code>```

It returns column names of table aean.

Now I have declared an array:

```<code>DECLARE colnames text[]
</code>```

How can I store select's output in colnames array.

Is there any need to initialize colnames?

答:
Regular:

```<code>SELECT post_id FROM posts WHERE(poster_name='John');

output: [
  {'post_id': 1},
  {'post_id': 2},
  {'post_id': 3},
]
</code>```

Using ARRAY_AGG:

```<code>SELECT ARRAY_AGG(post_id) FROM posts WHERE(poster_name='John');

output: [
 {[1, 2, 3]}
]
</code>```

Body:
My code is:

SELECT column_name
FROM information.SCHEMA.columns
WHERE table_name = 'aean'

It returns column names of table aean.

Now I have declared an array:

DECLARE colnames text[]

How can I store select's output in colnames array.

Is there any need to initialize colnames?

Body:
Regular:

SELECT post_id FROM posts WHERE(poster_name='John');

output: [
  {'post_id': 1},
  {'post_id': 2},
  {'post_id': 3},
]

Using ARRAY_AGG:

SELECT ARRAY_AGG(post_id) FROM posts WHERE(poster_name='John');

output: [
 {[1, 2, 3]}
]